Rotate List
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是非负实数,可能超过链表长度,所以需要计算链表长度。遍历一遍链表,得到链表长度length,并且将首尾相连,形成一个循环链表。指针指到链表尾处,再移动length-k%length个节点,到达链表中断处p。按如下操作,就能达到rotate list效果。
p->next=head;
p->next=NULL;
解题
c++版1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31/**
* 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 || k==0)
return head;
ListNode *p;
p=head;
int length=1;
while(p->next){
p=p->next;
length++;
}
p->next=head;
k=length-k%length;
while(k){
p=p->next;
k--;
}
head=p->next;
p->next=NULL;
return head;
}
};
python版
1 | # Definition for singly-linked list. |