61. Rotate List
一、问题描述
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个数字移动到前面去。如果k比链表的长度要大,就需要取模运算。(吃了没文化的亏╮(╯▽╰)╭)
Tow Pointers有人用fast slow指针来找末尾的那个位置,我还不知道怎么找。。
- 算法思路:遍历一遍链表,计算出链表的长度并把tail->next = head 形成一个循环链表。然后再从头开始往后遍历链表,走 length - k % length步,就找到新的链表尾部了,把链表断开就行了。想清楚了题目的意思其实并不难。
/**
* 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(head == NULL)return head;
ListNode* tail = head, *nTail = head;
int length = 1;
while(tail->next){
tail=tail->next;
length++;
}
tail->next = head;
int steps = length - k % length;
while (--steps){
nTail = nTail->next;
}
head = nTail->next;
nTail->next = NULL;
return head;
}
};