天天看點

Leetcode | C++ 61-RotateList

題目分析:

将一個連結清單向右旋轉

k

位。如

1 -> 2 -> 3 -> 4

向右旋轉3位則為

2 -> 3 -> 4 -> 1

解題思路

求對外連結表的長度len, 則我們需要移k%len位。找到需要斷開的位置重接一下即可。例子如上。

class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(!head) return head;
		ListNode *p = head, *q;
        int len = 1;
        while(p->next) {
            len++;
            p = p->next;
        }
        if(!(k %= len)) return head;//if k%len == 0, needn't do anything
        k = len-k;
		p->next = head;//let the last node point to head
		while(k--)
			p = p->next;//find the kth node
		head = p->next;
		p->next = NULL;//break the list
		return head;
    }
};