-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
reverseNodesInKGroup.cpp
111 lines (94 loc) · 2.31 KB
/
reverseNodesInKGroup.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// Source : https://oj.leetcode.com/problems/reverse-nodes-in-k-group/
// Author : Hao Chen
// Date : 2014-07-05
/**********************************************************************************
*
* 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
*
*
**********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *reverseList(ListNode *&head, int k);
ListNode *reverseKGroup(ListNode *head, int k) {
if (k<=0) return head;
ListNode fake(0);
fake.next = head;
ListNode* p = &fake;
while(p){
p->next = reverseList(p->next, k);
for(int i=0; p && i<k; i++){
p = p->next;
}
}
return fake.next;
}
ListNode *reverseList(ListNode *&head, int k){
ListNode* pEnd=head;
while (pEnd && k>0){
pEnd = pEnd->next;
k--;
}
if (k>0) return head;
ListNode *pHead=pEnd, *p=head;
while(p != pEnd){
ListNode *q = p->next;
p->next = pHead;
pHead = p;
p = q;
}
return pHead;
}
void printList(ListNode* h)
{
while(h!=NULL){
printf("%d ", h->val);
h = h->next;
}
printf("\n");
}
ListNode* createList(int a[], int n)
{
ListNode *head=NULL, *p=NULL;
for(int i=0; i<n; i++){
if (head == NULL){
head = p = new ListNode(a[i]);
}else{
p->next = new ListNode(a[i]);
p = p->next;
}
}
return head;
}
int main(int argc, char** argv)
{
int a[] = {1,2,3,4,5,6,7,8,9,10};
ListNode* pList = createList(a, sizeof(a)/sizeof(int));
int k =2;
if (argc>1){
k = atoi(argv[1]);
}
pList = reverseKGroup(pList, k);
printList(pList);
return 0;
}