题目要求:
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
.
比较直观的一个解法就是先求出链表长度,然后再确定从头节点位移到分割节点处的步数。接下来就是分割链表和拼接了。具体程序(8ms)如下:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* rotateRight(ListNode* head, int k) { 12 if(!head || !head->next || k == 0) 13 return head; 14 15 int len = 0; 16 ListNode *start = head; 17 while(start) 18 { 19 len++; 20 start = start->next; 21 } 22 k = len - k % len; 23 if(k == 0 || k == len) 24 return head; 25 26 ListNode *dummy = new(nothrow) ListNode(INT_MIN); 27 assert(dummy); 28 29 start = head; 30 for(int i = 0; i < k - 1; i++) 31 start = start->next; 32 33 dummy->next = start->next; 34 start->next = nullptr; 35 36 start = dummy; 37 while(start->next) 38 start = start->next; 39 start->next = head; 40 41 head = dummy->next; 42 delete dummy; 43 dummy = nullptr; 44 45 return head; 46 } 47 };
这题还有另一个很巧妙的解法:首先从head开始跑,直到最后一个节点,这时可以得出链表长度len。然后将尾指针指向头指针,将整个圈连起来,接着往前跑len – k%len,从这里断开,就是要求的结果了。
具体程序(12ms)如下:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* rotateRight(ListNode* head, int k) { 12 if(!head || !head->next || k == 0) 13 return head; 14 15 int len = 1; 16 ListNode *start = head; 17 while(start->next) 18 { 19 len++; 20 start = start->next; 21 } 22 k = len - k % len; 23 if(k == 0 || k == len) 24 return head; 25 26 start->next = head; 27 for(int i = 0; i < k; i++) 28 start = start->next; 29 30 head = start->next; 31 start->next = nullptr; 32 33 return head; 34 } 35 };