zoukankan      html  css  js  c++  java
  • 61. Rotate List

    Given a list, rotate the list to the right by k places, where k is non-negative.

    For example:
    Given 1->2->3->4->5->NULL and k = 2,
    return 4->5->1->2->3->NULL.

    1. 

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* rotateRight(ListNode* head, int k) {
            if(!head || !k || !head->next)
                return head;
            ListNode *p, *q=head, *r;
            int l=0, i;
            for(p=head; p; p=p->next)
                l++;
            k = k%l;
            for(i=0; i<k; i++)
            {
                if(!q->next)
                    q = head;
                else
                    q = q->next;
            }
            p=head;
            while(q->next)
            {
                p = p->next;
                q = q->next;
            }
            r = p->next;
            if(!r)
                return head;
            p->next = NULL;
            q->next = head;
            return r;
        }
    };

    2.

    先连成环,算长度。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* rotateRight(ListNode* head, int k) {
            if(!head || !k)
                return head;
            ListNode *p, *q=head, *r;
            int l=1, i;
            for(p=head; p->next; p=p->next)
                l++;
            p->next = head;
            k = l-k%l;
            for(i=0; i<k; i++)
                p = p->next;
            head=p->next;
            p->next=NULL;
            return head;
        }
    };
  • 相关阅读:
    javascript 高级程序设计 二
    javascript 高级程序设计 一
    js 立即执行函数
    thinkphp验证器
    thinkphp5 行为(钩子)扩展
    thinkphp5控制器
    修改tp5的默认配置文件的位置
    thinkphp5 model 模型与Db
    API接口设计,rest,soap
    tp5的路由
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5267998.html
Copyright © 2011-2022 走看看