forked from weiliu89/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverseLinkedList.II.cpp
125 lines (103 loc) · 2.39 KB
/
reverseLinkedList.II.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
// Source : https://oj.leetcode.com/problems/reverse-linked-list-ii/
// Author : Hao Chen
// Date : 2014-07-05
/**********************************************************************************
*
* Reverse a linked list from position m to n. Do it in-place and in one-pass.
*
* For example:
* Given 1->2->3->4->5->NULL, m = 2 and n = 4,
*
* return 1->4->3->2->5->NULL.
*
* Note:
* Given m, n satisfy the following condition:
* 1 ≤ m ≤ n ≤ length of list.
*
*
**********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *reverseBetween(ListNode *head, int m, int n) {
if (head==NULL || m>=n) return head;
ListNode fake(0);
fake.next = head;
ListNode *pBegin=&fake, *pEnd=&fake;
int distance = n - m ;
while(pEnd && distance>0){
pEnd = pEnd->next;
distance--;
}
while(pBegin && pEnd && m-1>0) {
pBegin = pBegin->next;
pEnd = pEnd->next;
m--;
}
if (pBegin==NULL || pEnd==NULL || pEnd->next == NULL){
return head;
}
ListNode *p = pBegin->next;
ListNode *q = pEnd->next->next;
ListNode *pHead = q;
while(p != q){
ListNode* node = p->next;
p->next = pHead;
pHead = p;
p = node;
}
pBegin->next = pHead;
return fake.next;
}
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;
}
ListNode* createList(int len) {
int *a = new int[len];
for(int i=0; i<len; i++){
a[i] = i+1;
}
ListNode* h = createList(a, len);
delete[] a;
return h;
}
int main(int argc, char** argv)
{
int l=5;
int m=2, n=4;
if (argc>1){
l = atoi(argv[1]);
}
if (argc>2) {
m = atoi(argv[2]);
}
if (argc>3) {
n = atoi(argv[3]);
}
ListNode* h = createList(l);
printList( h );
printList( reverseBetween(h , m, n) );
}