标签:
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==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;
}
};
标签:
原文地址:http://blog.csdn.net/kaitankedemao/article/details/44498705