leetcode--reverse-nodes-in-k-group--链表
2018-03-03 13:03
337 查看
Given a linked list, reverse the nodes of a linked list k at a time and return its modified 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
参考
http://blog.csdn.net/linhuanmars/article/details/19957455
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
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *reverse(ListNode *pre, ListNode *end) { if(!pre || !pre->next) return NULL; ListNode *head = pre->next; ListNode *cur = head->next; while(cur != end) { ListNode *next = cur->next; cur->next = pre->next; pre->next = cur; cur = next; } head->next = end; return head; } ListNode *reverseKGroup(ListNode *head, int k) { if(!head) return head; int count = 0; ListNode *newH = new ListNode(0); newH->next = head; ListNode *pre = newH; ListNode *cur = pre->next; while(cur) { ListNode *next = cur->next; ++count; if(count == k) { pre = reverse(pre, next); count = 0; } cur = next; } return newH->next; } };
参考
http://blog.csdn.net/linhuanmars/article/details/19957455
相关文章推荐
- LeetCode中几道链表反转相关题目(Reorder List、Rotate List、Reverse Nodes in k-Group)
- LeetCode之“链表”:Reverse Nodes in k-Group
- LeetCode | Reverse Nodes in k-Group(k个结点一组翻转链表)
- leetcode_c++:链表:Reverse Nodes in k-Group(025)
- leetcode_25题——Reverse Nodes in k-Group (链表)
- [LeetCode] Reverse Nodes in k-Group 每k个一组翻转链表
- LeetCode Reverse Nodes in k-Group(单链表连续分段反转)
- LeetCode (25) Reverse Nodes in k-Group (链表)
- LeetCode刷题笔记(链表):reverse-nodes-in-k-group
- 链表-leetcode 25 Reverse Nodes in k-Group
- 【leetcode 链表相关】Reverse Nodes in k-Group
- LeetCode-Reverse Nodes in k-Group-按组翻转链表-链表操作
- [LeetCode] Reverse Nodes in k-Group每k个一组翻转链表
- leetcode:Reverse Nodes in k-Group(以k为循环节反转链表)【面试算法题】
- 【LeetCode-面试算法经典-Java实现】【025-Reverse Nodes in k-Group(单链表中k个结点一组进行反转)】
- leetcode:Reverse Nodes in k-Group(以k为循环节反转链表)【面试算法题】
- [Leetcode] Reverse nodes in k group 每k个一组反转链表
- C实现 LeetCode->Reverse Nodes in k-Group (双指针大法)(单链表反转)
- [leetcode]Reverse Nodes in k-Group 反转以k个节点为一组的链表
- LeetCode 25 Reverse Nodes in k-Group(在K组链表中反转结点)(Linked List)(*)