-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathd45_linked_list_end.c
More file actions
113 lines (102 loc) · 1.81 KB
/
d45_linked_list_end.c
File metadata and controls
113 lines (102 loc) · 1.81 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct list_node
{
int data;
struct list_node *link;
};
typedef struct list_node node;
struct linked_list
{
node *head;
int size;
};
typedef struct linked_list list;
list* create_linked_list()
{
list* l = (list *)malloc(sizeof(list));
l->head = NULL;
l->size = 0;
return l;
}
bool check_empty(list* l)
{
return l->size == 0;
}
// insert at front
void insert_at_front(list* l,int val)
{
node *n = (node *)malloc(sizeof(node));
n->data = val;
n->link = l->head;
l->head = n;
l->size++;
}
//delete front
int delete_at_front(list* l)
{
if(check_empty(l))
{
printf("List Empty!");
return 0;
}
int val = l->head->data;
node *temp = l->head;
l->head = l->head->link;
free(temp);
l->size--;
return val;
}
// insert at end
void insert_at_end(list *l,int val)
{
node *n = (node *)malloc(sizeof(node));
n->data = val;
n->link = NULL;
node *temp = l->head;
while(temp != NULL && temp->link!=NULL)
{
temp = temp->link;
}
if(temp == NULL)
l->head = n;
else
temp->link = n;
l->size++;
}
int delete_at_end(list *l)
{
if(check_empty(l))
{
printf("List Empty");
return 0;
}
if(l->head->link == NULL)
{
int val = l->head->data;
free(l->head);
l->head = NULL;
return val;
}
node *temp = l->head;
while(temp->link->link!=NULL)
{
temp = temp->link;
}
int val = temp->link->data;
free(temp->link);
temp->link = 0;
return val;
}
int main(void)
{
list *l = create_linked_list();
insert_at_end(l,10);
insert_at_end(l,20);
while(!check_empty(l))
{
printf("%d\n",delete_at_end(l));
}
return 0;
}