Rotate List
来源:互联网 发布:java初级招聘北京 编辑:程序博客网 时间:2024/05/22 23:47
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->NULL
and k = 2
,
return 4->5->1->2->3->NULL
.
分析:三次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; }};
0 0
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- rotate-list
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- 系统性能loadrunner应用
- Ubuntu 12下整合Apache Web Server 和Tomcat
- 百度编辑器ueditor 在vs2008中的使用方法
- 实战DeviceIoControl 之一:通过API访问设备驱动程序
- TortoiseSVN中分支和合并实践
- Rotate List
- Oracle性能分析6:数据访问方式之索引扫描
- 状态模式State
- redis简易安装和说明
- 关于工作的吐槽
- web前后台的参数交互方式
- Android的BaseAdapter 里面setTag的作用
- Android 刷机Nexus5 4.4.3
- 指针与数组