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.
- 思路
先求出尾节点以及链表大小,然后重新连接,感觉链表的链接还是很直观的。
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(k==0 || !head)
return head;
ListNode* tail=head;//用来指向尾节点
ListNode* curr=head;//用来指向K之前的节点
int size=1; //用来记录链表的大小
while(tail->next)//让tail指向尾节点
{
tail = tail->next;
size++;
}
tail->next = head;//让尾节点指向头节点
k = k%size; //防止K大于size
int n=size-k-1; //计算循环几次可以到K之前的节点
while(n) //使curr指向K之前的节点
{
curr = curr->next;
n--;
}
head = curr->next; //修正头节点
curr->next = NULL; //修正新尾节点指向NULL
return head;
}
};
简化版
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)//从尾部开始的循环所以不用再-1
}
newH = tail->next;
tail->next = NULL;
return newH;
}
};