-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path203.c
98 lines (92 loc) · 2.04 KB
/
203.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
95
96
97
98
#include <stdlib.h>
#include <stdio.h>
struct ListNode
{
int val;
struct ListNode *next;
};
// Function to remove elements without using a dummy head
struct ListNode *removeElements1(struct ListNode *head, int val)
{
struct ListNode *pre = NULL;
struct ListNode *cur = head;
while (cur != NULL)
{
if (cur->val == val && pre == NULL)
{
struct ListNode *oldHead = head;
head = head->next;
cur = head;
free(oldHead);
}
else if (cur->val == val && pre != NULL)
{
pre->next = cur->next;
free(cur);
cur = pre->next;
}
else
{
pre = cur;
cur = cur->next;
}
}
return head;
}
// Function to remove elements using a dummy head
struct ListNode *removeElements2(struct ListNode *head, int val)
{
struct ListNode *dummyHead = (struct ListNode *)malloc(sizeof(struct ListNode));
dummyHead->next = head;
struct ListNode *pre = dummyHead;
struct ListNode *cur = head;
while (cur != NULL)
{
if (cur->val == val)
{
pre->next = cur->next;
free(cur);
cur = pre->next;
}
else
{
pre = cur;
cur = cur->next;
}
}
head = dummyHead->next;
free(dummyHead);
return head;
}
void printAllNodes(struct ListNode *head)
{
if (head == NULL)
{
printf("Empty!\n");
return;
}
while (head != NULL)
{
printf("%d ", head->val);
head = head->next;
}
printf("\n");
}
struct ListNode *newNode(int val)
{
struct ListNode *node = (struct ListNode *)malloc(sizeof(struct ListNode));
node->val = val;
node->next = NULL;
return node;
}
int main()
{
struct ListNode *head = newNode(7);
head->next = newNode(7);
head->next->next = newNode(7);
head->next->next->next = newNode(7);
printAllNodes(head);
head = removeElements2(head, 7);
printAllNodes(head);
return 0;
}