【LeetCode算法练习(C++)】Reverse Nodes in k-Group
2017-10-20 16:00
399 查看
题目:
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)
Runtime: 36 ms
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
相关文章推荐
- 算法练习(11):Reverse Nodes in k-Group
- leetcode_c++:链表:Reverse Nodes in k-Group(025)
- 【LeetCode算法练习(C++)】Swap Nodes in Pairs
- LeetCode Online Judge 题目C# 练习 - Reverse Nodes in k-Group
- LeetCode--Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- LEETCODE: Reverse Nodes in k-Group
- [leetcode]Reverse Nodes in k-Group 反转以k个节点为一组的链表
- Leetcode #25 Reverse Nodes in k-Group K区间链表交换 解题报告
- LeetCode(6) - Reverse Nodes in k-Group
- leetcode25~Reverse Nodes in k-Group
- LeetCode 025 Reverse Nodes in k-Group
- leetcode -- Reverse Nodes in k-Group -- 经典题目,要重写
- 【Leetcode】之Reverse Nodes in k-Group
- LeetCode-25-Reverse Nodes in k-Group(C语言实现)
- 【Leetcode】Reverse Nodes in k-Group
- LeetCode25 Reverse Nodes in k-Group
- [leetcode]Reverse Nodes in k-Group
- LeetCode - Refresh - Reverse Nodes in k-Group
- LeetCode中几道链表反转相关题目(Reorder List、Rotate List、Reverse Nodes in k-Group)