題目:
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.
分析:
將後面的k個node旋轉到鏈表的開頭。若k大於鏈表的長度,則應該先進行求餘,再進行鏈表旋轉。
思路:
1)計算鏈表的長度,計算在第幾個點,旋轉鏈表
2)找到該節點,將該節點的上一個節點的next設置爲NULL,將鏈表最後一個節點的next設置爲head。
代碼:
ListNode* rotateRight(ListNode* head, int k) {
if(!head) return head;
ListNode* l = head;
ListNode* last;
ListNode* p;
int len = 0;
int times = 0;
while(l)
{
len ++;
last = l;
l = l->next;
}
k = k%len;
if (k != 0)
{
l = head;
for(int i = 1; i < (len - k); i++)
{
l = l->next;
}
p = l ->next;
l->next = NULL;
last->next = head;
return p;
}
return head;
}
leetcode的測試用例,總是存在一個輸入爲空的情況,記住要額外處理一下。