[LeetCode] 61. Rotate List
来源:互联网 发布:单片机花贲浇花 编辑:程序博客网 时间:2024/06/10 18:32
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.
class Solution {public: ListNode* rotateRight(ListNode* head, int k) { if (head == nullptr || k == 0) return head; int n; ListNode **slow = &head, *fast = head; for (n = 1; n < k && fast->next != nullptr; n++) fast = fast->next; // deal with k >= n if (fast->next == nullptr) { k = k % n; if (k == 0) return head; fast->next = head; fast = head; int headpos = n - k; for (int i = 1; i < headpos; i++) fast = fast->next; ListNode *newhead = fast->next; fast->next = nullptr; return newhead; } // deal with k < n while (fast->next) { slow = &((*slow)->next); fast = fast->next; } ListNode *newhead = *slow; *slow = nullptr; fast->next = head; return newhead; }};
阅读全文
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
- 61. Rotate List LeetCode
- 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
- 165合并两个排序链表
- python小白进阶一:如何安装scikit learn库
- Spring框架中的单例模式(源码解读)
- java实现文件的复制
- 更新phonegap2.9打包的dojo开发页面的ios app遇到的问题
- [LeetCode] 61. Rotate List
- libssl.so.10: cannot open shared object file: No such file or directory
- 几种进程间的通信方式
- 适当的时候,用递归取代for循环
- Python编程规范
- msp430的DCO校准值被清除后该如何处理
- EDK学习笔记——C函数整理
- 连续子数组的最大和
- React Native开发笔记