天天看點

LeetCode算法題目: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.

分析:

先周遊一遍,得對外連結表的長度len,然後把連結清單首尾相連(構成環),然後令K=len-K%len,得出截斷環的位置,移動相應位置後,将環截斷即得到結果。

代碼:

/**
 * 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==nullptr||k==)
        return  head;
        int len=;
        ListNode *p=head;
        while(p->next){
            len++;
            p=p->next;
        }
        p->next=head;
        k=len-k%len;
        for(int i=;i<k;i++){
            p=p->next;
        }
        head=p->next;
        p->next=nullptr;
        return head;
    }
};