您的位置:首页 > 其它

LeetCode 61. Rotate List

2017-10-02 22:11 302 查看
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
.

分析:

旋转链表,新链表的头节点应该是len-k%len的位置,首先计算链表的长度,并且需要一个指针找到尾部节点,因为尾部节点要用来连接头部节点。

然后找到循环移动后的最后一个节点,然后下一个节点的地址就是新节点的头节点,再将后面的节点为null,这里要注意顺序。

最后将尾部节点与头节点链接。

/**
* 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||head->next==NULL||k==0) return head;
ListNode *l=head,*p=head,*newhead=head,*tail=head;
int len=0;
while(l!=NULL){
if(l->next==NULL) tail=l;//找到尾部节点,因为尾部节点要连接第一个节点
l=l->next;
len++;
}
k=k%len;
if(k==0) return head;
for(int i=0;i<len-k-1;i++){
p=p->next;
newhead=newhead->next;//找到循环节点的最后一个位置
}
newhead=newhead->next;//newhead做为头节点
p->next=NULL;
tail->next=head;//尾部节点连接头部节点
return newhead;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: