-
Notifications
You must be signed in to change notification settings - Fork 0
/
Reverse_nodes_in_k-Group
78 lines (69 loc) · 2.15 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
/*
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.
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) {
if (head==NULL) return head;
if (k<=1) return head;
ListNode *dummyHead=new ListNode(INT_MIN);
dummyHead->next=head;
ListNode *p=dummyHead, *q=dummyHead;
while(p!=NULL&&q!=NULL)
{
int counter=k;
//shift q
while(counter>0)
{
q=q->next;
if (q==NULL) return dummyHead->next;
counter--;
}
//reverse within the group
counter=k;
while(counter-1>0)
{
ListNode *temp=p->next;
p->next=temp->next;
temp->next=q->next;
q->next=temp;
counter--;
}
counter=k;
//move p and q to the node before the next group
while(counter-1>0)
{
q=q->next;
counter--;
}
p=q;
}
return dummyHead->next;
}
};
REMARK:
1.IDEA: In order to reverse a list, we should swap nodes in pair, one from the front and the other from the back. We either swap pairs of nodes or swap their values. In this problem, we are not allowed to swap value, so we swap nodes.
To be specific: assume k=3,given list 1->2->3->4->5->6->7..,now we want to reverse the sublist 4->5->6.We define 2 fixed pointer p and q:p points to 3,q points to 6. Then the reverse goes like:
step1:1->2->3->4->5->6->7
p q
step2:1->2->3 ->5->6->4->7
p q
step3:1->2->3-> 6->5->4->7
p q
2.Time complexity: O(n),space: O(1)