61. Rotate List
来源:互联网 发布:分布式数据库的安全性 编辑:程序博客网 时间:2024/05/21 10:04
Given a list, rotate the list to the right by k places, where k is non-negative.
Example:
Given 1->2->3->4->5->NULL and k = 2,return 4->5->1->2->3->NULL.
思路:首先遍历链表算出链表长度len,然后计算出k%len,即所需要的最小rotate次数,然后把链表分成两段交换即可。
/** * 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) return NULL; //计算链表的长度 ListNode* tmp = head; int len = 0; while (tmp) { len++; tmp = tmp->next; } //旋转k%len次得到的结果和旋转k次得到的结果是相同的 k = k % len; if (k == 0) return head; //post->next指向的是倒数第k个元素 ListNode* pre = head; ListNode* post = head; for (int i = 0; i < k; i++) { pre = pre->next; } while (pre->next) { pre = pre->next; post = post->next; } //post->next前后的链表互换位置,即得到最终结果 ListNode* newHead = post->next; pre->next = head; post->next = NULL; return newHead; }};
阅读全文
0 0
- [LeetCode]61.Rotate List
- 61. Rotate List
- LeetCode --- 61. Rotate List
- [Leetcode] 61. Rotate List
- 61. Rotate List
- [leetcode] 61.Rotate List
- [leetcode] 61. Rotate List
- 61. Rotate List
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- [leetcode] 61. Rotate List
- 61. Rotate List
- 61. Rotate List
- 61. Rotate List LeetCode
- leetcode 61. Rotate List
- 61. Rotate List
- 61. Rotate List
- 61. Rotate List
- 高精度乘法
- 第五届图灵杯1865
- 《GO并发编程实战》—— 锁的使用
- 字符串求字节数和长度
- spring自动装配
- 61. Rotate List
- 纯CSS实现select的placeholder效果
- PREV-5 错误票据
- 12.03周日
- object_detection API论文Speed/accuracy trade-offs for...的详细中文翻译
- 11.优化服务器设置
- 通过例子学习spark dataframe -- transformations函数(2)
- 6.12
- python从控制台接收输入创建二叉树