A linked list is a way to store a collection of elements. Like an array these can be character or integers. Each element in a linked list is stored in the form of a node.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
void create();
void sl_insert(int data);
void sl_delete();
void display();
typedef struct node
{
int data;
struct node *link;
}snode;
snode *head,*tail,*temp;
void create()
{
head=tail=NULL;
}
void sl_insert(int data)
{
snode *newnode;
int pos,i=1;
newnode = (snode*)malloc(sizeof(snode));
newnode->data=data;
newnode->link=NULL;
if(head==NULL)
{
head=newnode;
tail=newnode;
}
else
{
printf("\n Enter your position");
scanf("%d",&pos);
if(pos==1)
{
newnode->link=head;
head=newnode;
}
else
for(temp=head;i<pos-1&&temp->link!=NULL;temp=temp->link,i++);
if(temp->link==NULL)
{
temp->link=newnode;
tail=newnode;
}
else
{
newnode->link=temp->link;
temp->link=newnode;
}
}
}
void sl_delete()
{
snode *temp,*next;
int pos,i=1;
if(head==NULL)
printf("\n No linked list");
if(head==tail)
{
free(head);
free(tail);
head=NULL;
tail=NULL;
}
else{
printf("\nEnter position to delete");
scanf("%d",&pos);
if(pos==1)
{
temp=head;
head=head->link;
free(temp);
}
else{
for(temp=head;i<pos-1&&temp->link!=NULL;temp=temp->link,i++);
if(temp->link==NULL)
{
free(tail);
tail=temp;
tail->link=NULL;
}
else
{
next=temp->link;
temp->link=next->link;
free(next);
next=NULL;
}
}
}
}
void display()
{
if(head==NULL)
printf("\nNo list");
else
{
for(temp=head;temp!=NULL;temp=temp->link)
{
printf("%d",temp->data);
}
}
}
void main()
{
int ch,data;
while(1)
{
printf("\n Enter your required option");
printf("\n1:Create\n2:Insert\n3:delete\n4:Display\n5:Exit");
scanf("%d",&ch);
switch(ch)
{
case 1:create();
break;
case 2:
printf("\n Enter a number");
scanf("%d",&data);
sl_insert(data);
break;
case 3:
sl_delete();
break;
case 4:
display();
break;
case 5:
exit(0);
break;
}
}
}