Skip to content

Commit 05c767e

Browse files
Merge pull request #157 from Ritika-Das/patch-1
Create Linked_List.c
2 parents 0636916 + 188a4c7 commit 05c767e

File tree

1 file changed

+124
-0
lines changed

1 file changed

+124
-0
lines changed

Linked_List.c

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
/*Write a C program that uses functions to perform the following:
2+
a) Create a singly linked list of integers
3+
b) Delete a given integer from the above linked list
4+
c) Display the contents of the above list after deletion
5+
CODE:-*/
6+
#include<stdio.h>
7+
#include<stdlib.h>
8+
struct node
9+
{
10+
int data;
11+
struct node *next;
12+
};
13+
struct node *head, *tail = NULL;
14+
void addNode(int data)
15+
{
16+
struct node *newNode=(struct node*)malloc(sizeof(struct node));
17+
newNode->data=data;
18+
newNode->next=NULL;
19+
if(head==NULL)
20+
{
21+
head=newNode;
22+
tail=newNode;
23+
}
24+
else
25+
{
26+
tail->next = newNode;
27+
tail = newNode;
28+
}
29+
}
30+
void display()
31+
{
32+
struct node *current = head; // the node current will point to head
33+
if(head==NULL)
34+
{
35+
printf("List is empty\n");
36+
return;
37+
}
38+
printf("\nNodes of singly linked list: \n");
39+
while(current!= NULL)
40+
{
41+
printf("%d ", current->data); // each node is printed
42+
current = current->next;
43+
}
44+
printf("\n");
45+
}
46+
void delete()
47+
{
48+
struct node *ptr,*ptr1;
49+
int item,i=0,flag,loc,j;
50+
ptr = head;
51+
if(ptr == NULL)
52+
{
53+
printf("\nEmpty List\n");
54+
}
55+
else
56+
{
57+
printf("\nWhich integer do you want to delete?\n");
58+
scanf("%d",&item);
59+
while (ptr!=NULL)
60+
{
61+
if(ptr->data == item)
62+
{
63+
printf("Integer found at node %d ",i+1);
64+
flag=0;
65+
loc=i;
66+
break;
67+
}
68+
else
69+
{
70+
flag=1;
71+
}
72+
i++;
73+
ptr = ptr -> next;
74+
}
75+
if(flag==1)
76+
{
77+
printf("Integer not found!\n");
78+
}
79+
}
80+
ptr=head;
81+
for(j=0;j<loc;j++)
82+
{
83+
ptr1 = ptr;
84+
ptr = ptr->next;
85+
if(ptr == NULL)
86+
{
87+
printf("\nDeletion is not possible!");
88+
return;
89+
}
90+
}
91+
ptr1->next = ptr ->next;
92+
free(ptr);
93+
printf("\nDeleted node %d \n",loc+1);
94+
}
95+
int main()
96+
{
97+
int n,m,data;
98+
printf("How many nodes do you want to create?\n");
99+
scanf("%d",&n);
100+
for(int i=0;i<n;i++)
101+
{
102+
printf("Integer node %d data : ",(i+1));
103+
scanf("%d",&data);
104+
addNode(data);
105+
}
106+
display();
107+
delete();
108+
display();
109+
}
110+
/*OUTPUT:-
111+
How many nodes do you want to create?
112+
4
113+
Integer node 1 data : 13
114+
Integer node 2 data : 16
115+
Integer node 3 data : 19
116+
Integer node 4 data : 21
117+
Nodes of singly linked list:
118+
13 16 19 21
119+
Which integer do you want to delete?
120+
19
121+
Integer found at node 3
122+
Deleted node 3
123+
Nodes of singly linked list:
124+
13 16 21*/

0 commit comments

Comments
 (0)