Rotate List
2014-09-11 10:34
369 查看
Rotate List
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->NULLand k =
2,
return
4->5->1->2->3->NULL.
题目:将链表右旋转k个位置。
分析:三次reverse,前半部分reverse,后半部分reverse,然后所有的reverse一下。 注意找到倒数的第k个数,k有可能大于链表长度,要取余数。
代码:
/**
* 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) return head;
//find k from end
ListNode *fast=head;
int t=0;
while(fast && (t<k)){
fast=fast->next;
t++;
}
if(fast==NULL && t==k) return head;//k等于链表长度
if(fast==NULL){k=k%t;}//k大于链表长度
t=0;
fast=head;
while(fast && (t<k)){ //继续找到倒数第k个位置,将链表分成两部分
fast=fast->next;
t++;
}
ListNode *p=head;
while(fast->next){
p=p->next;
fast=fast->next;
}
//p 指向 4前一个
ListNode *part2=p->next;
p->next=NULL;
ListNode *re1=reverse(head);//前半部分reverse,此时head里边是链表的末尾元素
ListNode *re2=reverse(part2);//后半部分reverse
head->next=re2;//将两部分连接起来
return reverse(re1);
}
ListNode *reverse(ListNode *head){//返回的head 是反转后的末尾
if(head==NULL || head->next==NULL) return head;
ListNode *pre=head;
ListNode *cur=head->next;
head->next=NULL;//末尾节点
while(cur){
ListNode *t=cur;
cur=cur->next;
t->next=pre;
pre=t;
}
return pre;
}
};
相关文章推荐
- [Leetcode] Rotate List
- LeetCode 61: Rotate List
- Rotate List
- 【LeetCode】Rotate List
- Leetcode | Rotate List
- Leetcode NO.61 Rotate List
- [leetcode][list] Rotate List
- Rotate List
- [LeetCode]Rotate List
- leetcode_061 Rotate List
- Rotate List
- LeetCode 61. Rotate List
- leetcode第一刷_Rotate List
- LintCode 170. Rotate List
- Rotate List
- [leetcode]Rotate List
- 61. Rotate List
- Leetcode: Rotate List
- Leetcode--Rotate List
- Rotate List