leetcode系列(41)Reverse Nodes in K-Group
来源:互联网 发布:加强网络舆情管理 编辑:程序博客网 时间:2024/06/04 19:35
Given a linked list, reverse the nodes of alinked list k at a time and return its modified list.If thenumber of nodes is not a multiple of k then left-out nodes inthe end should remain as it is.You may not alter the values in the nodes, onlynodes itself may be changed.Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you shouldreturn: 2->1->4->3->5
For k = 3, you shouldreturn: 3->2->1->4->5
解答:这个题目就是考察链表操作过程中细心的程度,还有一个翻转链表的辅助函数(稍微有些变动,末尾节点不一定是nullptr),用dummy_node辅助减少代码难度。
class Solution {public: ListNode* reverseKGroup(ListNode* head, int k) { if (k <= 1) { return head; } auto dummy = ListNode(0); dummy.next = head; auto start = head; auto ptr = &dummy; while (start != nullptr) { auto end = start; for (int i = 1; i < k; i++) { end = end->next; if (end == nullptr) { return dummy.next; } } ptr->next = _reverse(start, end->next); ptr = start; start = start->next; } return dummy.next; }private: // reverse nodes [start, end] ListNode* _reverse(ListNode* start, ListNode* end) { ListNode* pre = nullptr; auto cur = start; while (cur != end) { auto nxt = cur->next; cur->next = pre; pre = cur; cur = nxt; } start->next = cur; return pre; }};
0 0
- leetcode系列(41)Reverse Nodes in K-Group
- 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
- LeetCode | 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
- LeetCode题解: Reverse Nodes in k-Group
- 【Leetcode】Reverse Nodes in k-Group
- LeetCode Reverse Nodes in k-Group
- [Leetcode] Reverse Nodes in k-Group (Java)
- 软件缺陷(defect)和bug的严重性(Severity)和优先级(Priority)
- 【软考之路】软件开发模型
- ym——Android快速开发框架(持续更新!)
- 用筛法求之N内的素数。
- 基数排序
- leetcode系列(41)Reverse Nodes in K-Group
- og4j-over-slf4j与slf4j-log4j12共存stack overflow异常分析
- java的一些散知识点
- Tab导航栏的实现
- WGS-84、北京54、西安80空间坐标转平面坐标
- leetcode系列(42)Remove Duplicates from Sorted Array & Remove Element
- 加密原理
- poj 3273- Monthly Expense(最大值最小化)-二分
- struts中的ActionContext是什么?