Linked List
Linked List
#include<stdio.h>
#include<stdlib.h>
node *head;
void create();
void display();
void insert();
void delete();
void reverse();
void display_reverse(node *);
int main()
{
int ch;
char cho;
create();
display();
printf("\n\nLinked List Operation\n");
do
{
printf("\nEnter your choice\n");
printf("\n1.Insert\n2.Delete\n3.DisplayReverse\n4.Reverse\n");
scanf("%d",&ch);
switch(ch)
{
case 1:insert();
break;
case 2:delete();
break;
case 3:display_reverse(head);
break;
case 4:reverse();
display();
break;
}
void create()
{
node *p,*c;
char ch;
p=(node*)malloc(sizeof(node));
printf("\nEnter first node data\n");
scanf("%d",&p->data);
head=p;
do
{
c=(node*)malloc(sizeof(node));
printf("\nEnter next node data\n");
scanf("%d",&c->data);
p->next=c;
p=c;
printf("\nY/N for more nodes\n");
ch=getchar();
}while(ch=='y'||ch=='Y');
p->next=NULL;
void display()
{
node *p;
printf("\n");
for(p=head;p!=NULL;p=p->next)
printf("%d->",p->data);
}
void insert()
{
int ch,info;
char cho;
node *p,*c;
do
{
p=(node*)malloc(sizeof(node));
if(p==NULL)
printf("\nOVERFLOW\n");
else
{
printf("\nWhere do u want to insert:\n 1.Beginning\n2.Anywhere\
n3.End\n");
scanf("%d",&ch);
printf("\nEnter node data:\n");
scanf("%d",&p->data);
switch(ch){
case 1:
p->next=head;
head=p;
display();
break;
case 2:
printf("\nEnter the node after which you want to insert the new
node\n");
scanf("%d",&info);
for(c=head;c->data!=info;c=c->next);
p->next=c->next;
c->next=p;
display();
break;
case 3:for(c=head;c->next!=NULL;c=c->next);
c->next=p;
p->next=NULL;
display();
break;
}
}
printf("\nPress Y to insert more nodes??");
cho=getchar();
}while(cho=='y'||cho=='Y');
}
void delete()
{
int ch,info;
char cho;
node *p,*c;
do
{
if(head==NULL)
printf("\nLinked List is Empty\n");
else
{
printf("\nWhich node u want to delete\n1.Beginning\n2.Anywhere\
n3.End\n");
scanf("%d",&ch);
switch(ch)
{
case 1: p=head;
head=head->next;
free(p);
display();
break;
case 2: printf("\nEnter the node you want to delete \n");
scanf("%d",&info);
for(c=head;c->data!=info;c=c->next)
{p=c;}
p->next=c->next;
free(c);
display();
break;
case 3: for(c=head;c->next->next!=NULL;c=c->next);
p=c->next;
c->next=NULL;
free(p);
display(); break;
}
void reverse()
{
node *p,*c,*t;
p=head;
t=NULL;
while(p!=NULL)
{
c=p->next;
p->next=t;
t=p;
p=c;
}
head=t;
}
void sort()
{
int temp;
node *p,*c;
for(p=head;p->next!=NULL;p=p->next)
{
for(c=p->next;c!=NULL;c=c->next)
{
if(p->data>c->data)
{
temp=p->data;
p->data=c->data;
c->data=temp;
}
}
}
}
Output
Enter first node data
23
23->12->
1.Insert
2.Delete
3.DisplayReverse
4.Reverse
1
42->23->12->