2017-09-11 LeetCode_025 Reverse Nodes in k-Group
2017-09-11 13:17
513 查看
25. Reverse Nodes in k-Group
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:
For k = 2, you should return:
For k = 3, you should return:
solution:
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
solution:
class Solution {
2
public:
3
ListNode* reverseKGroup(ListNode* head, int k) {
4
int d = 0;
5
ListNode *p = head;
6
while (p != NULL) {
7
d++; p = p->next;
8
}
9
if (d < k) return head;
10
if (k <= 1) return head;
11
p = head;
12
ListNode *q = head->next, *r = head->next->next;
13
int k_ = k-2;
14
while (k_--) {
15
q->next = p;
16
p = q; q = r; r = r->next;
17
}
18
q->next = p;
19
head->next = reverseKGroup(r, k);
20
return q;
21
}
22
};
相关文章推荐
- 025 Reverse Nodes in k-Group [Leetcode]
- leetcode_c++:链表:Reverse Nodes in k-Group(025)
- LeetCode 025 Reverse Nodes in k-Group
- leetcode解题方案--025--Reverse Nodes in k-Group
- Java for LeetCode 025 Reverse Nodes in k-Group
- [LeetCode]题解(python):025-Reverse Nodes in k-Group
- LeetCode-025 Reverse Nodes in k-Group
- leetcode 025 —— Reverse Nodes in k-Group
- LeetCode 025 Reverse Nodes in k-Group
- 【LeetCode-面试算法经典-Java实现】【025-Reverse Nodes in k-Group(单链表中k个结点一组进行反转)】
- leetcode:Reverse Nodes in k-Group
- [leetcode]Reverse Nodes in k-Group
- 【leetcode】【单链表】【25】Reverse Nodes in k-Group
- LeetCode 25 Reverse Nodes in k-Group (C,C++,Java,Python)
- LeetCode | Reverse Nodes in k-Group
- leetcode之Reverse Nodes in k-Group
- Reverse Nodes in k-Group leetcode
- LeetCode 笔记系列六 Reverse Nodes in k-Group [学习如何逆转一个单链表]
- LeetCode--Reverse Nodes in k-Group
- LeetCode_Reverse Nodes in k-Group