[Leetcode] #61 Rotate List
来源:互联网 发布:淘宝的评论管理在哪里 编辑:程序博客网 时间:2024/06/07 06:38
Discription:
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
.
Solution:
ListNode* rotateRight(ListNode* head, int k) {if (head == NULL) return NULL;int size = 0;ListNode *p1 = head, *p2 = head;while (p1){size++;p1 = p1->next;}k = k%size;p1 = head;for (int i = 0; i < k; i++){p2 = p2->next;}while (p2->next){p1 = p1->next;p2 = p2->next;}p2->next = head;head = p1->next;p1->next = NULL;return head;}
ListNode* rotateRight(ListNode* head, int k) {if (!head) return head;int len = 1; // number of nodesListNode *newH, *tail;newH = tail = head;while (tail->next) // get the number of nodes in the list{tail = tail->next;len++;}tail->next = head; // circle the linkif (k %= len){for (auto i = 0; i<len - k; i++) tail = tail->next; // the tail node is the (len-k)-th node (1st node is head)}newH = tail->next;tail->next = NULL;return newH;}
附:Leetcode源代码见我的GitHub
0 0
- LeetCode 61: Rotate List
- [leetcode 61] Rotate List
- [leetcode #61]Rotate List
- leetcode || 61、Rotate List
- leetcode[61]:Rotate List
- LeetCode 61: Rotate List
- LeetCode(61) Rotate List
- LeetCode 61 Rotate List
- leetcode 61: Rotate List
- Leetcode#61||Rotate List
- [Leetcode]#61 Rotate List
- leetcode 61:Rotate List
- 【leetcode】【61】Rotate List
- 【LeetCode-61】Rotate List
- LeetCode 61 - Rotate List
- ( Leetcode 61 ) Rotate List
- leetcode-Rotate List-61
- LeetCode 61 Rotate List
- 寒假篇37
- React Native开发之常用第三方控件
- RAD模型
- 串口返回红外键值
- 机器学习在工程中使用要点
- [Leetcode] #61 Rotate List
- 请教大神,在Java中GSON解析 JSON 怎么解析
- POJ 1321 棋盘问题
- 高精度——数楼梯
- 寒假篇38
- 红外输出串口
- Android开发之RecyclerView的使用全解
- 简单易学的机器学习算法——马尔可夫链蒙特卡罗方法MCMC
- 什么是 Tango 姿势?