-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedList.c
119 lines (108 loc) · 2.32 KB
/
linkedList.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
// Insert at beginning
// insert at end
//Delete node by value
//Display linked list
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node *next;
};
struct Node *start = NULL;
struct Node* createNode(){
return (struct Node*)malloc(sizeof(struct Node));
}
int isEmpty(){
if(start == NULL) return 1;
return 0;
}
void insertBeginning(int element){
struct Node *new = createNode();
new->data = element;
new->next = start;
start = new;
}
void insertEnd(int element){
struct Node *new = createNode();
new->data = element;
new->next = NULL;
if(start==NULL){
start = new;
return;
}
struct Node *temp = start;
while(temp->next!=NULL) temp = temp->next;
temp->next = new;
return;
}
void deleteNodeByValue(int element){
if(start==NULL){
printf("List is empty, cannot delete!!\n");
return;
}
struct Node *tempCurrent = start;
struct Node *tempPrevious = NULL;
struct Node *tempNext = NULL;
while(tempCurrent != NULL){
if(tempCurrent->data == element){
tempNext = tempCurrent->next;
free(tempCurrent);
if(tempPrevious==NULL) start = tempNext;
else tempPrevious->next = tempNext;
printf("Element Deleted!!\n");
return;
}
tempPrevious = tempCurrent;
tempCurrent = tempCurrent->next;
}
printf("Element not found\n");
return;
}
void display(){
if(start == NULL){
printf("List is empty!!\n");
return;
}
struct Node *temp = start;
while(temp!=NULL){
printf("%d\t", temp->data);
temp = temp->next;
}
printf("\n");
}
void main(){
int flag = 1;
int option;
int element;
while(flag){
printf("\n****************************************************************************************************\n");
printf("Select from following\n1. Insert at Biginning\n2. Inser at End\n3. Delete by value\n4. Display\n>> ");
scanf("%d", &option);
switch(option){
case 1:
printf("Enter the element to insert: ");
scanf("%d", &element);
insertBeginning(element);
break;
case 2:
printf("Enter the element to insert: ");
scanf("%d", &element);
insertEnd(element);
break;
case 3:
if(isEmpty() == 0){
display();
printf("Enter the element to insert: ");
scanf("%d", &element);
deleteNodeByValue(element);
}
else printf("Liste is empty!!\n");
break;
case 4:
display();
break;
default:
flag = 0;
}
}
}