dsa
dsa
h>
#include<stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *head=NULL, *temp, *loc, *p;
void insertbeg()
{
p=(struct node*)malloc(sizeof(struct node));
printf("Enter element: ");
scanf("%d",&p->data);
if(head==NULL)
{
head=p;
p->link=NULL;
}
else
{
p->link=head;
head=p;
}
}
void insertpos()
{
p=(struct node*)malloc(sizeof(struct node));
int pos;
if(head==NULL)
{
insertbeg();
}
else
{
printf("Enter the element: ");
scanf("%d",&p->data);
printf("Enter the postion: ");
scanf("%d",&pos);
temp=head;
for(int i=1;i<pos-1;i++)
{
temp=temp->link;
}
p->link=temp->link;
temp->link=p;
}
}
void insertend()
{
p=(struct node*)malloc(sizeof(struct node));
if(head==NULL)
{
insertbeg();
}
else
{
printf("Enter the element: ");
scanf("%d",&p->data);
for(temp=head;(temp->link)!=NULL;temp=temp->link)
{
}
temp->link=p;
p->link=NULL;
}
}
void deletebeg()
{
if(head==NULL)
{
printf("Empty List!");
}
else
{
temp=head;
head=head->link;
free(temp);
}
}
void deletepos()
{
if(head==NULL)
{
printf("Empty List!");
}
else if(head->link==NULL)
{
deletebeg();
}
else
{
printf("Enter deletion position: ");
int pos;
scanf("%d",&pos);
temp=head;
loc=head->link;
for(int i=1;i<pos-2;i++)
{
temp=temp->link;
loc=loc->link;
}
temp->link=loc->link;
free(loc);
}
}
void deleteend()
{
if(head==NULL)
{
printf("Empty List!");
}
else
{
for(temp=head,loc=head->link;(loc->link)!=NULL;temp=temp->link,loc=loc->link)
{
}
temp->link=NULL;
free(loc);
}
}
void display()
{
if(head==NULL)
{
printf("Empty List!");
}
else
{
printf("The linked list is as follows: \n");
for(temp=head;temp!=NULL;temp=temp->link)
{
printf("%d\t",temp->data);
}
printf("\n");
}
}
void main()
{
int ch1,ch2;
while(1)
{
printf("1) Insertion\n2) Deletion\n3) Display\n4) Exit\nEnter Choice: ");
scanf("%d",&ch1);
switch(ch1)
{
case 1: printf("1) Beginning\n2) At Postion\n3) End\n4) Go Back\n");
scanf("%d",&ch2);
switch(ch2)
{
case 1: insertbeg();
break;
case 2: insertpos();
break;
case 3: insertend();
break;
case 4: break;
}
break;
case 3: display();
break;
case 4: exit(0);
default: printf("Invalid Choice! Try Again!");
break;
}
}
}