-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedlist2.c
More file actions
108 lines (84 loc) · 2.82 KB
/
linkedlist2.c
File metadata and controls
108 lines (84 loc) · 2.82 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
#include <stdio.h>
#include <stdlib.h>
struct node{
int value;
struct node* next;
};
struct node* insert(struct node* list, int value){
struct node* new = malloc(sizeof(struct node));
new->value = value;
new->next = NULL;
//if list is empty
if(list == NULL){
return new;
}
struct node* current = list;
struct node* previous = NULL;
// going through list to see if value should be added to beginning, (somewhere in the) middle or end
while(current != NULL && current->value != value){
previous = current;
current = current->next;
}
// repointing the next pointer of new node - now new next always points to current
new->next = current;
// being added to beginning
if(previous == NULL){
return new;
// making a new list where new element is at beginning and the whole previous list is copied(appended to new)
// since new->next is already appointed to current hence older list auto gets appended to new
}
// somewhere in the middle - none of them equal to NULL (this will also be used to add to end)
previous->next = new;
new->next = current;
return list;
}
void printall(struct node* list){
struct node* p = list;
while(p != NULL){
printf("%d\t", p->value);
p = p->next;
}
}
void clear(struct node* list) // since we are allocating memory we need to free it
{
struct node* p = list;
while(p != NULL){
struct node* temp = p; // temporary node holding list
p = p->next; // traversing through list
free(temp); // freeing the list
}
}
struct node* delete(struct node* list, int value){
struct node* current = list;
struct node* previous = NULL;
// going through list to see position of value being deleted
while(current != NULL && current->value <= value){
previous = current;
current = current->next;
}
if(current == NULL) return list;
// if current is NULL that means the whole list has been traveresed and there was no match hence nothing to delete
if(previous == NULL){
list = list->next;
free(current); // getting rid of the current pointer (which is pointing to the list)
// since previous points to null it is not associated to list hence does not need to be freed
return list;
}
// previous and current both not NULL
previous->next = current->next;
free(current);
return list;
}
int main(){
struct node *list;
list = insert(list, 3);
list = insert(list, 1);
list = insert(list, 5);
list = insert(list, 4);
printall(list);
list = delete(list, 4);
printf("\nafter deletion\n");
printall(list);
clear(list);
return 0;
}