LeetCode61- rotation list
Recent national epidemic is serious, stay at home with nothing to do, once again ready to spring resort, recently brush problem, record it! And again, Wuhan Come on, go out remember to wear a mask!
1, title
Given a list, the list of rotation, each of the node list to the right by k positions, wherein k is non-negative.
Example:
输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL
2, thinking
3, Code
c++
class Solution {
public:
ListNode* rotateRight(ListNode* head, int k) {
if(!head) return NULL;
//计算链表长度
int n=0;
for(auto p=head;p;p=p->next) n++;
//对k取模
k%=n;
auto first=head,second=head;
//first指针先走K步
while(k--) first=first->next;
//first、second指针同时前进,直到尾部为止
while(first->next)
{
first=first->next;
second=second->next;
}
//first指针指向头结点、secode的下个元素成为头结点,second指针指向null
first->next=head;
head=second->next;
second->next=NULL;
return head;
}
};
Java
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(!head) return null;
for(ListNode p=head;p;p=p.next) n++;
k%=n;
ListNode first=head,second=head;
for(int i=1;i<=k;i++)
{
first=first.next;
}
while(first.next!=null)
{
first=first.next;
second=second.next;
}
first.next=head;
head=second.next;
second.next=null;
return head;
}
}