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个元素放到左边。
// 16 ms
/**
* 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;
int len = 0;
ListNode* it = head;
while(it)
{
it = it->next;
len++;
}
k %= len;
if(k==len || k==0)
return head;
it = head;
while(it->next)
it = it->next;
ListNode *NewHead = head, *NewTail = head;
for(int i=0;i<len-k-1;i++)
NewTail = NewTail->next;
NewHead = NewTail->next;
NewTail->next = NULL; //顺序很重要
it->next = head;
return NewHead;
}
};
附:solution区解法。先构成一个循环链表,然后直接从结尾开始计数,直到停止。
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head)
return head;
int len=1; // number of nodes
ListNode *newH, *tail;
newH = tail = head;
while(tail->next) // get the number of nodes in the list
{
tail = tail->next;
len++;
}
tail->next = head; // circle the link
if(k %= len)
{
for(auto i=0; i<len-k; i++)
tail = tail->next; // the tail node is the (len-k)-th node (1st node is head)
}
newH = tail->next;
tail->next = NULL;
return newH;
}
};