forked from sunstick/code-street
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse_node_k_group.cpp
63 lines (53 loc) · 1.56 KB
/
reverse_node_k_group.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
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
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
ListNode dummy(0);
ListNode *tail = &dummy;
tail -> next = head;
ListNode *kbegin = NULL;
ListNode *kend = NULL;
ListNode *node = head;
int i = 0;
while (node) {
if (i % k == 0)
kbegin = node;
if (i % k == k - 1)
kend = node;
node = node -> next;
if (i % k == k - 1) {
kend -> next = NULL;
ListNode *prev = NULL;
ListNode *t = kbegin;
while (t) {
ListNode *temp = t -> next;
t -> next = prev;
prev = t;
t = temp;
}
tail -> next = kend;
tail = kbegin;
tail -> next = node;
}
i++;
}
return dummy.next;
}
};