【LeetCode算法练习(C++)】Reverse Nodes in k-Group
来源:互联网 发布:qq飞车f22猛禽性能数据 编辑:程序博客网 时间:2024/06/12 19:28
题目:
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
链接:Reverse Nodes in k-Group
解法:设置虚拟头结点便于操作,每轮检查是否还有足够的节点可供转置,之后转化为链表转置问题。时间O(n)
class Solution {public: ListNode* reverseKGroup(ListNode* head, int k) { if (k < 2) return head; ListNode* h = new ListNode(0); h->next = head; ListNode* p = h; while (enoughNode(p, k)) { ListNode* p1 = p->next; ListNode* p2 = p1->next; ListNode* p3 = p2->next; ListNode* nxt = p; for (int i = 0; i < k; i++) { nxt = nxt->next; } p1->next = nxt->next; nxt = p1; for (int i = 0; i < k - 1; i++) { p2->next = p1; p1 = p2; p2 = p3; if (p3) p3 = p3->next; } p->next = p1; p = nxt; } ListNode* tmp = h; h = h->next; delete(tmp); return h; } bool enoughNode(ListNode* head, int k) { for (int i = 0; i < k; i++) { if (!head->next) return false; head = head->next; } return true; }};
Runtime: 36 ms
阅读全文
0 0
- 【LeetCode算法练习(C++)】Reverse Nodes in k-Group
- 算法练习(11):Reverse Nodes in k-Group
- leetcode 25:Reverse Nodes in k-Group(C)
- LeetCode算法题目:Reverse Nodes in k-Group
- [LeetCode] 025. Reverse Nodes in k-Group (Hard) (C++/Java)
- LeetCode 之 Reverse Nodes in k-Group — C 实现
- [leetcode-25]Reverse Nodes in k-Group(C)
- [LeetCode练习题-C语言] 25. Reverse Nodes in k-Group
- 【LeetCode】 25. Reverse Nodes in k-Group C语言
- LeetCode-25-Reverse Nodes in k-Group(C语言实现)
- LeetCode:Reverse Nodes in k-Group
- LeetCode: Reverse Nodes in k-Group
- LeetCode : Reverse Nodes in k-Group
- leetcode 42: Reverse Nodes in k-Group
- [Leetcode] reverse nodes in K-Group
- [LeetCode]Reverse Nodes in k-Group
- LeetCode-Reverse Nodes in k-Group
- LeetCode - Reverse Nodes in k-Group
- Postgresql服务管理
- Java Reflect 反射
- 云数据库管理与数据迁移
- vue 1.x 交互-仿百度下拉列表
- 管理分区表
- 【LeetCode算法练习(C++)】Reverse Nodes in k-Group
- 总结JS 常用函数
- spring、springmvc、mybatis整合配置(注解)
- Java反射打印类的信息,包括类的成员函数、成员变量(只获取成员函数)
- (TODO)Empirical Analysis of Predictive Algorithm for Collaborative Filtering
- 通过3D-MAX制作三维地图模型
- HTTP协议详解
- VS2017 Xamarin扫描二维码并跳转网页
- 题目51:管闲事的小明