forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
92.c
94 lines (80 loc) · 1.81 KB
/
92.c
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
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode *reverseBetween(struct ListNode *head, int m, int n) {
struct ListNode *front, *rear; /* front and rear node of reversed list */
struct ListNode *left, *right; /* left and right linked point */
struct ListNode *p, *q, *t;
front = rear = left = right = NULL;
int len = n - m + 1;
t = head;
m -= 1;
while (m--) {
left = t;
t = t->next;
}
rear = t;
p = q = NULL;
while (len--) {
q = t->next;
t->next = p;
p = t;
t = q;
}
right = t;
front = p;
/* left to front, rear to right */
if (left) {
left->next = front;
}
else {
head = front;
}
rear->next = right;
return head;
}
int main() {
struct ListNode *l1 = (struct ListNode *)calloc(5, sizeof(struct ListNode));
struct ListNode *p = l1;
int i;
for (i = 1; i <= 4; i++) {
p->val = i;
p->next = p + 1;
p++;
}
p->val = 5;
p->next = NULL;
p = l1;
while (p) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
p = reverseBetween(l1, 2, 4);
while (p) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
struct ListNode *l2 = (struct ListNode *)calloc(2, sizeof(struct ListNode));
l2->val = 3;
l2->next = l2 + 1;
l2->next->val = 5;
l2->next->next = NULL;
p = l2;
while (p) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
p = reverseBetween(l2, 1, 2);
while (p) {
printf("%d ", p->val);
p = p->next;
}
printf("\n");
return 0;
}