Rotate List
来源:互联网 发布:python 跨平台吗? 编辑:程序博客网 时间:2024/06/03 07:55
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: ListNode* rotateRight(ListNode* head, int k) { if(head==NULL) return NULL; ListNode* dummy=new ListNode(-1); dummy->next=head; ListNode *tail=getRightk(dummy,k); if(tail==dummy) return head; dummy->next=tail->next; ListNode *tmp=tail; while(tmp->next){ tmp=tmp->next; } tmp->next=head; tail->next=NULL; return dummy->next; } ListNode* getRightk(ListNode* dummy,int k){ ListNode* right=dummy->next; ListNode* left=dummy->next; ListNode* leftpre=dummy; int length=0; ListNode* tmp=dummy->next; while(tmp){ length++; tmp=tmp->next; } if(k%length==0) return dummy; for(int i=0;i<k%length;i++){ right=right->next; } while(right!=NULL){ right=right->next; leftpre=leftpre->next; } return leftpre; }};
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
- C++之日志打印
- android带动画的圆形进度条
- django.db.utils.ProgrammingError: (1146, "Table 'test_b.products_category' doesn't exist")
- android 图片自定义三级缓存实现以及原理、图片错位解决
- ofbiz中widget框架页面生成原理
- Rotate List
- oracle高级sql的参考资料
- Ubuntu12.04 lts 安装gcc 4.8
- MR11
- 编程的智慧
- Android知识点记录
- GridView学习
- 用Scala推荐的Eclipse作为IDE开发Spark 1.5.1的程序
- 打开exe并隐藏程序窗口