LeetCode 61 Rotate List
来源:互联网 发布:php var_export 编辑:程序博客网 时间:2024/05/21 10:26
题意:
将链表旋转k次,每次旋转表示为1->2->...->N变为N->1->2->...->N-1。
思路:
首先要测链表总长度n,因为k如果比n大,那么旋转整圈是没意义的。
然后求出实际要旋转的次数x,最后就是简单的链表在n-x分割再头尾合并了。
代码:
/** * 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) { ListNode *tail; int n = 0; for (ListNode *i = head; i != NULL; i = i->next) { ++n; tail = i; } if (n == 0 || k % n == 0) { return head; } k = n - k % n; ListNode *it = head; for (int i = 1; i < k; ++i) { it = it->next; } ListNode *ot = it->next; it->next = NULL; tail->next = head; return ot; }};
阅读全文
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
- (108)调用事件调度器
- javaScript中with函数用法实例分析
- 怎么恢复回收站清空的文件
- IDE文件识别错误导致开发人员没有找出错误
- 七天学会ASP.NET MVC (五)——Layout页面使用和用户角色管理
- LeetCode 61 Rotate List
- Node.Js运行Express框架中遇到的问题(备忘)
- js阻止冒泡
- Bug Check 0xC9: DRIVER_VERIFIER_IOMANAGER_VIOLATION
- 新浪微博用户兴趣建模系统架构
- 智能指针之auto_ptr
- 内存与flash
- apache服务器无法启动,发生服务特定错误:1
- Access denied for user 'root'@'localhost' (using password: YES)