F How to display all nodes in a single link list and can do all operation? | CodeTheta

How to display all nodes in a single link list and can do all operation?

April 17, 2014

/* http://native-code.blogspot.com */

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
typedef struct link
{
int data;
struct link *next;
}node;
node *ins_beg(node*, int);
node *ins_last(node*, int);
node *ins_before_node(node*, int);
node *ins_aft_node(node*, int k, int n);
void display(node*);
void main()
{
int n,k,d,ch;
node *head=NULL;
while(1)
{
printf("/* http://native-code.blogspot.com */");
printf("\n\n1-->Insert at begining\n2-->Insert at last\n3-->insert before a  given node\n4-->Insert after given node\n5-->Display\n6-->EXIT\n\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter value for new node:\n");
scanf("%d",&n);
head=ins_beg(head,n);
break;
case 2:
printf("Enter data of the node:\n");
scanf("%d", &d);
head=ins_last(head, d);
break;
case 3:
printf("Enter value of node before which to insert:\n");
scanf("%d", &k);
head=ins_before_node(head, k);
break; 
case 4:
printf("Enter value for new node:\n");
scanf("%d",&n);
printf("Enter value at node after which to insert:\n");
scanf("%d",&k);
head=ins_aft_node(head,k,n);
break;
case 5:
display(head);
printf("\n");
break;
case 6:
exit(0);
default:
printf("Wrong choice.\n");
}
}
getch();
}
node* ins_beg(node *h, int n)
{
node *temp, *r=h;
temp=(node *)malloc(sizeof(node));
temp->data=n;
temp->next=NULL;
if(h==NULL)
{
h=temp;
}
else
{
temp->next=h;
h=temp;
}
return(h);
}
node *ins_aft_node(node *h,int k,int n)
{
node *temp,*p,*l;
temp=p=l=NULL;
temp=(node *)malloc(sizeof(node));
temp->data=n;
temp->next=NULL;
p=h;
while(p->data!=k)
p=p->next;
l=p->next;
p->next = temp;
temp->next=l;
return(h);
}
void display(node *h)
{
node *r=h;
while(r!=NULL)
{
printf("%d-->",r->data);
r=r->next;
}
printf("NULL");
}
node *ins_last(node *h, int d)
{
node *temp, *r=h;
temp=(node*) malloc(sizeof(node));
temp->data=d;
temp->next=NULL;
if(h==NULL)
h=temp;
else
{
while(r->next!=NULL)
r=r->next;
r->next=temp;
}
return(h);
}
node *ins_before_node(node *h, int k)
{
int z;
node *p,*r,*temp;
p=h;r=temp=NULL;
while(p->data!=k)
{
r=p;
p=p->next;
}
printf("Enter value of new node:\n");
scanf("%d", &z);
temp=(node*) malloc (sizeof(node));
temp->data=z;
temp->next=NULL;
r->next =temp;
temp->next =p;
return(h);
}

/* http://native-code.blogspot.com */

Post a Comment