-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path92.reverse-linked-list-ii-recursion.c
More file actions
64 lines (54 loc) · 1.19 KB
/
92.reverse-linked-list-ii-recursion.c
File metadata and controls
64 lines (54 loc) · 1.19 KB
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
#include <stdlib.h>
#include <stdio.h>
// Definition for singly-linked list.
struct ListNode
{
int val;
struct ListNode *next;
};
struct ListNode *successor = NULL;
struct ListNode *reverseN(struct ListNode *head, int n)
{
if (n == 1)
{
successor = head->next;
return head;
}
struct ListNode *last = reverseN(head->next, n - 1);
head->next->next = head;
head->next = successor;
return last;
}
struct ListNode *reverseBetween(struct ListNode *head, int m, int n)
{
if (m == 1)
{
return reverseN(head, n);
}
head->next = reverseBetween(head->next, m - 1, n - 1);
return head;
}
int main(int argc, char const *argv[])
{
struct ListNode *list = malloc(sizeof(struct ListNode));
struct ListNode *p = list;
for (size_t i = 1; i < 6; i++)
{
p->val = i;
if (i == 5)
break;
p->next = malloc(sizeof(struct ListNode));
p = p->next;
}
p->next = NULL;
list = reverseBetween(list, 2, 4);
struct ListNode *prev;
while (list != NULL)
{
prev = list;
printf("%d ", list->val);
list = list->next;
free(prev);
}
return 0;
}