Given a list, rotate the list to the right by k places, where k is non-negative. ...
Description
Given a list, rotate the list to the right by k places, where k is non-negative.
Example
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
思路
- 先遍歷一遍鏈表,記錄長度,同時記錄最後一個節點
- 修正k的大小,找到旋轉後的頭結點,和它的前一個節點
- 按照題目要求重新鏈接鏈表
代碼
/**
* 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(k == 0) return head;
if(!head) return NULL;
ListNode *ptr = head, *tail = NULL;
int len = 0;
//找出鏈表的長度
while(ptr){
len++;
tail = ptr;
ptr = ptr->next;
}
//修正k的值
k = k % len;
if(k== 0) return head;
int step = len - k + 1;
ListNode *fastPtr = head;
ptr = head;
while(step - 1 > 0){
step--;
ptr = fastPtr;
fastPtr = fastPtr->next;
}
if(fastPtr){
tail->next = head;
ptr->next = NULL;
return fastPtr;
}
return head;
}
};