Singly Linklist:- Hii Friends, The Below code will show you how we can create singly Linklist in Data Structure using C. we can simply create the singly linklist using the pointers and malloc function to insert and delete element dynamically.
#include<stdio.h>
#include<conio.h>
#include<malloc.h>
#include<process.h>
struct node
{
int info;
struct node *next;
};
typedef struct node NODE;
NODE *node=NULL,*start=NULL,*end=NULL;
void insert();
void del();
void disp();
void main()
{
int ch;
clrscr();
while(1)
{
printf("\n1:Insert");
printf("\n2:Delete");
printf("\n3:Display");
printf("\n4:Exit");
printf("\n\tEnter Your Choice:-");
scanf("%d",&ch);
switch(ch)
{
case 1:
insert();
break;
case 2:
del();
break;
case 3:
disp();
break;
case 4:
exit(1);
default:
printf("\n\tOption Not Available");
break;
}
}
getch();
}
void insert()
{
node=(NODE *)malloc(sizeof(NODE));
printf("\n\tEnter the Element:-");
scanf("%d",&node->info);
node->next=NULL;
if(start==NULL)
{
start=node;
end=node;
}
else
{
end->next=node;
end=node;
}
}
void del()
{
NODE *temp=start;
NODE *p=start;
int no,flag=0;
if(start==NULL)
printf("\n\tNo Element to Delete Please Insert Element First");
else
{
printf("\n\tEnter the Element you Want to Delete:- ");
scanf("%d",&no);
while(p!=NULL)
{
if(p->info==no && p->info==start->info) //The Deleted element at First Position in Linklist
{
flag=1;
printf("\n\t%d is Delete ",p->info);
start=start->next;
break;
}
else if(p->info==no && p->info!=start->info && p->info!=end->info) //The Deleted element at Middle in the Linklist
{
flag=1;
printf("\n\t%d is Delete ",p->info);
temp->next=p->next;
p=temp;
break;
}
else if(p->info==no && p->info==end->info) //The Deleted element at Last Position in Linklist
{
flag=1;
printf("\n\t%d is Delete ",p->info);
end=temp;
end->next=NULL;
break;
}
else
{
temp=p;
p=p->next;
}
}
if(flag==0)
printf("\n\tElement You Want to Delete Not in Linklist");
}
}
void disp()
{
NODE *temp;
temp=start;
if(start==NULL)
{
printf("\n\tNo Element to Display Please Insert Element First");
}
else
{
while(temp!=NULL)
{
printf("%d\n",temp->info);
temp=temp->next;
}
}
}
0 Comment(s)