-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdelete-x.c
87 lines (67 loc) · 1.19 KB
/
delete-x.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
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node* next;
}
Node;
Node* head;
void Insert(int x)
{
Node* temp = malloc(sizeof(Node));
if (temp == NULL)
{
printf("Memory allocation failed");
exit(1);
}
temp->data = x;
temp->next = head;
head = temp;
}
void Print(void)
{
Node* current = head;
printf("List is: [ ");
while (current != NULL)
{
printf("%d ", current->data);
current = current->next;
}
printf("]\n");
}
void Delete(int x)
{
Node* prev = head;
while(prev->next != NULL)
{
if (head->data == x)
{
head = head->next;
free(prev);
return;
}
if (prev->next->data == x)
{
Node* current = prev->next;
prev->next = current->next;
free(current);
return;
}
prev = prev->next;
}
printf("Not Found\n");
}
int main(void)
{
head = NULL;
for (int i = 8; i > 0; i -= 2)
Insert(i);
Print();
int x;
printf("Enter a number: ");
scanf("%d", &x);
Delete(x);
Print();
return 0;
}