您的位置:首页 > 其它

LeetCode - Rotate List

2013-08-24 17:32 288 查看
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
.
/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:

int getSize(ListNode *head){
ListNode *p=head;
int counter=0;
while(p){
p=p->next;
counter++;
}
return counter;
}

ListNode *rotateRight(ListNode *head, int k) {
if(k<=0||head==NULL){
return head;
}
k%=getSize(head);//注意这里,k的大小可能超过链表长度
if(k==0){
return head;
}

ListNode *p=head, *q=head, *r;
int counter=0;
while(q&&counter<k){//循环直到q指向正数第k+1个结点
q=q->next;
counter++;
}

while(q->next){//循环直到q指向最后一个结点时,p正好指向倒数第k+1个结点
p=p->next;
q=q->next;
}

q=p->next;
p->next=NULL;

p=q;//p、q分别指向需要提前的结点的首、尾结点
while(q->next){
q=q->next;
}
q->next=head;
head=p;
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: