Skip to content

Commit 676fe97

Browse files
Create singly_linked_list
1 parent ca2eeba commit 676fe97

File tree

1 file changed

+125
-0
lines changed

1 file changed

+125
-0
lines changed

singly_linked_list

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
struct list{
4+
int key;
5+
struct list *next;
6+
};
7+
struct list *head,*tail=NULL;
8+
void add_node(int key){
9+
struct list *newnode=(struct list*)malloc(sizeof(struct list));
10+
newnode->key=key;
11+
newnode->next=NULL;
12+
if(head==NULL){
13+
head=newnode;
14+
tail=newnode;
15+
}
16+
else{
17+
tail->next=newnode;
18+
tail=newnode;
19+
}
20+
}
21+
void add_node_beg(int key){
22+
struct list *newnode=(struct list*)malloc(sizeof(struct list));
23+
newnode->key=key;
24+
newnode->next=head;
25+
head=newnode;
26+
}
27+
void add_node_end(int key){
28+
struct list *newnode=(struct list*)malloc(sizeof(struct list));
29+
newnode->key=key;
30+
newnode->next=NULL;
31+
tail=newnode;
32+
}
33+
void add_node_mid(int key,int index){
34+
struct list *newnode=(struct list*)malloc(sizeof(struct list));
35+
newnode->key=key;
36+
newnode->next=NULL;
37+
if(head==NULL){
38+
head=newnode;
39+
tail=newnode;
40+
}
41+
else{
42+
struct list *temp,*current;
43+
temp=head;
44+
current=NULL;
45+
for(int i=0;i<index;i++){
46+
current=temp;
47+
temp=temp->next;
48+
}
49+
current->next=newnode;
50+
newnode->next=temp;
51+
}
52+
}
53+
void delete_beg(){
54+
if(head==NULL){
55+
printf("\nList is empty");
56+
}
57+
else{
58+
struct list *temp;
59+
temp=head;
60+
head=head->next;
61+
free(temp);
62+
}
63+
}
64+
void delete_mid(int index){
65+
if(head==NULL){
66+
printf("\nList is empty");
67+
}
68+
else{
69+
struct list *temp,*current;
70+
temp=head;
71+
current=NULL;
72+
for(int i=0;i<index;i++){
73+
temp=temp->next;
74+
75+
}
76+
current=temp->next;
77+
temp->next=current->next;
78+
free(current);
79+
}
80+
}
81+
void isempty(){
82+
if(head==NULL){
83+
printf("\nList is empty");
84+
}
85+
else{
86+
printf("\nList is not empty");
87+
}
88+
}
89+
void lastpos(){
90+
printf("\nLast value of the list is:\n");
91+
printf("%d\n",tail->key);
92+
}
93+
void display(){
94+
struct list *current = head;
95+
if(head==NULL){
96+
printf("List is empty\n");
97+
return;
98+
}
99+
printf("Nodes of singly linked list:\n");
100+
while(current!=NULL){
101+
printf("%d\n",current->key);
102+
current=current->next;
103+
}
104+
}
105+
106+
int main(){
107+
add_node(1);
108+
add_node(2);
109+
add_node(3);
110+
add_node(4);
111+
display();
112+
isempty();
113+
lastpos();
114+
add_node_beg(0);
115+
display();
116+
add_node_end(5);
117+
display();
118+
add_node_mid(7,3);
119+
display();
120+
delete_beg();
121+
display();
122+
delete_mid(4);
123+
display();
124+
return 0;
125+
}

0 commit comments

Comments
 (0)