-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path876.middle-of-the-linked-list-recursion.c
65 lines (56 loc) · 1.23 KB
/
876.middle-of-the-linked-list-recursion.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
#include <stdlib.h>
#include <stdio.h>
// Definition for singly-linked list.
struct ListNode
{
int val;
struct ListNode *next;
};
struct ListNode *mid = NULL;
int length = 0;
struct ListNode *middleNodeCount(struct ListNode *head, int count)
{
if (head->next == NULL)
{
length = count + 1;
if ((count + 1) == (length / 2 + 1))
mid = head;
return head;
}
middleNodeCount(head->next, ++count);
int midNumber = length / 2 + 1;
if (count == midNumber)
mid = head;
return head;
}
struct ListNode *middleNode(struct ListNode *head)
{
int count = 0;
middleNodeCount(head, count);
return mid;
}
int main(int argc, char const *argv[])
{
struct ListNode *list = malloc(sizeof(struct ListNode));
struct ListNode *p = list;
int length = 3;
for (size_t i = 1; i < length + 1; i++)
{
p->val = i;
if (i == length)
break;
p->next = malloc(sizeof(struct ListNode));
p = p->next;
}
p->next = NULL;
list = middleNode(list);
struct ListNode *prev;
while (list != NULL)
{
prev = list;
printf("%d ", list->val);
list = list->next;
free(prev);
}
return 0;
}