Leetcode Rotate List

OpenSoucre發表於2014-06-23

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處斷開,即可

    ListNode *rotateRight(ListNode *head, int k) {
        if(head == NULL || k == 0  )  return head;
        ListNode *p = head;
        int len = 1;
        while(p->next){len++;p=p->next;};
        p->next = head;
        k = len-k;
        int step = 0;
        while(step < k){
            p=p->next;
            step++;
        }
        head = p->next;
        p->next = NULL;
        return head;
    }

 

相關文章