forked from dimpeshmalviya/C-Language-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinked_list_example.c
More file actions
80 lines (68 loc) · 1.5 KB
/
linked_list_example.c
File metadata and controls
80 lines (68 loc) · 1.5 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
* linked_list_example.c
* Singly linked list with insert, delete, and print operations.
* Compile: gcc -std=c11 -Wall -Wextra -o linked_list_example linked_list_example.c
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int val;
struct Node *next;
} Node;
Node *create_node(int v) {
Node *n = malloc(sizeof(*n));
if (!n) return NULL;
n->val = v;
n->next = NULL;
return n;
}
void push_front(Node **head, int v) {
Node *n = create_node(v);
if (!n) return;
n->next = *head;
*head = n;
}
void delete_value(Node **head, int v) {
Node **cur = head;
while (*cur) {
if ((*cur)->val == v) {
Node *tmp = *cur;
*cur = tmp->next;
free(tmp);
return;
}
cur = &(*cur)->next;
}
}
void print_list(const Node *head) {
const Node *it = head;
while (it) {
printf("%d -> ", it->val);
it = it->next;
}
puts("NULL");
}
void free_list(Node *head) {
while (head) {
Node *t = head;
head = head->next;
free(t);
}
}
int main(void) {
Node *head = NULL;
push_front(&head, 3);
push_front(&head, 7);
push_front(&head, 5);
push_front(&head, 9);
printf("List after inserts: ");
print_list(head);
delete_value(&head, 5);
printf("List after deleting 5: ");
print_list(head);
delete_value(&head, 9);
printf("List after deleting 9: ");
print_list(head);
free_list(head);
return 0;
}