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大于或等于链表的长度n,所以实际效果等同于循环右移k%n次。
- 遍历单链表,计算出其长度n,并保存指向最后一个结点的尾指针tail
- 对k做预处理,k = k % n
- 顺序遍历单链表,定位到第n-k个结点
- 保存第n-k个结点的后继结点p,将tail的next置为head,并将原来的Head置为q,同时将第n-k个结点的next置为NULL。
需要注意的空链表和n==k的情况。
下面贴上代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* getLength(ListNode* head,int& len){
ListNode* p = head;
len = 1;
while (p&&p->next){
len++;
p = p->next;
}
return p;
}
ListNode *rotateRight(ListNode *head, int k) {
int len;
if (head){
ListNode* tail = getLength(head, len);
k = k%len;
int count = len - k;
ListNode* p = head;
while (p&&count > 1){
p = p->next;
count--;
}
ListNode* q = p->next;
p->next = NULL;
if (q){
tail->next = head;
head = q;
}
}
return head;
}
};