-
Notifications
You must be signed in to change notification settings - Fork 0
/
Reverse Nodes in k-Group
82 lines (63 loc) · 1.68 KB
/
Reverse Nodes in k-Group
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* 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) {
if (head==NULL) return head;
ListNode *dummy=new ListNode(0);
ListNode *begin=new ListNode(0);
ListNode *begin_prev=new ListNode(0);
ListNode *end=new ListNode(0);
ListNode *end_next=new ListNode(0);
ListNode *temp=new ListNode(0);
dummy->next=head;
begin_prev=dummy;
begin=head;
end=head;
int indicator=0;
int i=0;
//int initial=0;
while (indicator==0) {
i=0;
while ((i<k-1)&&(end!=NULL)) {
end=end->next;
i++;
}
if ((i==k-2)&&(end!=NULL)) {
indicator=0;
end_next=end->next;
// if (initial=0) dummy->next=end;
}
else indicator=1;
ListNode *prev=new ListNode(0);
ListNode *current=new ListNode(0);
ListNode *temp=new ListNode(0);
prev=begin;
current=begin->next;
if (indicator==0) {
i=0;
while (i<k-1) {
temp=current->next;
current->next=prev;
prev=current;
current=temp;
i++;
}
begin=end_next;
end=begin;
begin_prev->next=end;
begin_prev=prev;
}
else {
begin_prev->next=begin;
}
}
return dummy->next;
}
};