题目描述
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.
Solution 1(截断重组思路)
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if(head==NULL||head->next==NULL) return head;
ListNode *pre=new ListNode(-1);
pre->next=head;
int ListLen=0,pos;
ListNode *p=head,*q,*r;
while(p!=NULL)
{
++ListLen;
p=p->next;
}
pos=ListLen-k%ListLen;
if(pos==ListLen) return head;
p=head;
for(int i=0;i<pos-1;++i)
p=p->next;
q=pre->next;
pre->next=p->next;
r=p;
while(r->next!=NULL)
r=r->next;
r->next=q;
p->next=NULL;
return pre->next;
}
};
Solution 2 (将链表首尾相接成一个循环链表)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/*
题目;给定一个链表,将链表旋转到右边的k个位置,其中k是非负的。
例如:
1->2->3->4->5->NULL,为K = 2,
返还4->5->1->2->3->NULL。
*/
/*
分析:先遍历一遍,得出链表长度len,注意k可能会大于len,因此k%=len。
将尾结点next指针指向首节点,形成一个环,接着往后跑len-k步,从这里断开,就是结果
*/
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if(head==nullptr||k==0)
return head;
int len=1;
ListNode *p=head;
while(p->next){
//遍历一遍,求出链表长度
len++;
p=p->next;
}
k=len-k%len;
p->next=head;//首尾相连
for(int step=0;step<k;step++){
p=p->next;//接着往后跑
}
head=p->next;//新的首节点
p->next=nullptr;//断开环
return head;
}
};
Solution 3(常规循环思路,一步一步来)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* lpre(ListNode *phead)
{
if(phead==NULL||phead->next==NULL) return phead;
while(phead->next->next!=NULL)
phead=phead->next;
return phead;
}
ListNode *rotateRight(ListNode *head, int k) {
if(head==NULL||head->next==NULL) return head;
ListNode *pre=new ListNode(-1);
pre->next=head;
ListNode *lp=lpre(pre->next);
for(int i=0;i<k;++k)
{
lp->next->next=pre->next;
pre->next=lp->next;
lp->next=NULL;
lp=lpre(pre->next);
}
return pre->next;
}
};