1. 程式人生 > >Rotate List 連結串列的迴圈移動

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.

/**
 * 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==NULL||head->next==NULL)
            return head;
            
        ListNode *pre,*tmp;
        ListNode *z=new ListNode(-1);
        z->next=head;
        
        ListNode *cur=head;
        int i,len=1;
        while(cur->next)
        {
            len++;
            cur=cur->next;
        }
        cur->next=head;
        k=k%len;
        
        pre=z;
        for(i=0;i<len-k;i++)
        {
            pre=pre->next;//斷開的前驅
        }
        tmp=pre->next;
        pre->next=NULL;
        head=tmp;
        
        delete z;
        return head;
    }
};