Skip to content

Commit b4f4ea7

Browse files
committed
"Reverse Linked List II"
1 parent eca5403 commit b4f4ea7

File tree

2 files changed

+95
-1
lines changed

2 files changed

+95
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ them with C++ Language.
102102
| 95 | [Unique Binary Search Trees II] | [C++](src/95.cpp) |
103103
| 94 | [Binary Tree Inorder Traversal] | [C](src/94.c) |
104104
| 93 | [Restore IP Addresses] | |
105-
| 92 | [Reverse Linked List II] | |
105+
| 92 | [Reverse Linked List II] | [C](src/92.c) |
106106
| 91 | [Decode Ways] | [C](src/91.c) |
107107
| 90 | [Subsets II] | |
108108
| 89 | [Gray Code] | |

src/92.c

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
4+
struct ListNode {
5+
int val;
6+
struct ListNode *next;
7+
};
8+
9+
struct ListNode *reverseBetween(struct ListNode *head, int m, int n) {
10+
struct ListNode *front, *rear; /* front and rear node of reversed list */
11+
struct ListNode *left, *right; /* left and right linked point */
12+
struct ListNode *p, *q, *t;
13+
front = rear = left = right = NULL;
14+
15+
int len = n - m + 1;
16+
t = head;
17+
m -= 1;
18+
while (m--) {
19+
left = t;
20+
t = t->next;
21+
}
22+
23+
rear = t;
24+
p = q = NULL;
25+
while (len--) {
26+
q = t->next;
27+
t->next = p;
28+
p = t;
29+
t = q;
30+
}
31+
right = t;
32+
front = p;
33+
34+
/* left to front, rear to right */
35+
if (left) {
36+
left->next = front;
37+
}
38+
else {
39+
head = front;
40+
}
41+
rear->next = right;
42+
43+
return head;
44+
}
45+
46+
int main() {
47+
struct ListNode *l1 = (struct ListNode *)calloc(5, sizeof(struct ListNode));
48+
struct ListNode *p = l1;
49+
50+
int i;
51+
for (i = 1; i <= 4; i++) {
52+
p->val = i;
53+
p->next = p + 1;
54+
p++;
55+
}
56+
p->val = 5;
57+
p->next = NULL;
58+
59+
p = l1;
60+
while (p) {
61+
printf("%d ", p->val);
62+
p = p->next;
63+
}
64+
printf("\n");
65+
66+
p = reverseBetween(l1, 2, 4);
67+
while (p) {
68+
printf("%d ", p->val);
69+
p = p->next;
70+
}
71+
printf("\n");
72+
73+
struct ListNode *l2 = (struct ListNode *)calloc(2, sizeof(struct ListNode));
74+
l2->val = 3;
75+
l2->next = l2 + 1;
76+
l2->next->val = 5;
77+
l2->next->next = NULL;
78+
79+
p = l2;
80+
while (p) {
81+
printf("%d ", p->val);
82+
p = p->next;
83+
}
84+
printf("\n");
85+
86+
p = reverseBetween(l2, 1, 2);
87+
while (p) {
88+
printf("%d ", p->val);
89+
p = p->next;
90+
}
91+
printf("\n");
92+
93+
return 0;
94+
}

0 commit comments

Comments
 (0)