Tuesday, 4 December 2012

Singly Linked List Program

//Program For Singly Linked List//

#include<stdio.h>

#include<conio.h>

#include<alloc.h>

 

struct node

{

int data;

struct node *next;

}*first=NULL;

 

void insert(int val)

{

struct node *curr,*new1;

new1=(struct node*)malloc(sizeof(struct node));

new1->data=val;

new1->next=NULL;

 

if(first==NULL)

{

first=new1;

return;

}

curr=first;

while(curr->next!=NULL)

{

curr=curr->next;

}

curr->next=new1;

}

void display()

{

struct node *curr;

if(first==NULL)

{

printf("\n link list is empty");

return;

}

curr=first;

while(curr!=NULL)

{

printf("%d-->",curr->data);

curr=curr->next;

}

}

void delnode (int val)

{

struct node *curr, *prev;

if(first==NULL)

{

printf("\n link list is empty");

return;

}

curr=first;

while(curr->data!=val && curr!=NULL)

{

prev=curr;

curr=curr->next;

}

if(curr==NULL)

{

printf("\n value is not found");

return;

}

prev->next=curr->next;

free(curr);

}

void insertaft(int val,int key)

{

struct node *curr,*new1;

if(first==NULL)

{

printf("\n link list is empty");

return;

}

new1=(struct node*)malloc(sizeof(struct node));

new1->data=val;

new1->next=NULL;

curr=first;

while(curr->data!=key && curr!=NULL)

{

curr=curr->next;

}

if(curr==NULL)

{

printf("\n key is not found");

return;

}

new1->next=curr->next;

curr->next=new1;

}

void insertbfr(int val,int key)

{

struct node *new1,*curr,*prev;

new1=(struct node*)malloc(sizeof(struct node));

new1->data=val;

new1->next=NULL;

curr=first;

if(first->data==key)

{

new1->next=first;

first=new1;

return;

}

while(curr->data!=key && curr!=NULL)

{

prev=curr;

curr=curr->next;

}

if(curr==NULL)

{

printf("\n key not found");

return;

}

prev->next=new1;

new1->next=curr;

}

 

void main()

{

int ch,val,key;

clrscr();

do

{

printf("\n!!------menu------!!");

printf("\n  1. Insert        ");

printf("\n  2. Display       ");

printf("\n  3. Delete        ");

printf("\n  4. Insert after " );

printf("\n  5. Insertt before");

printf("\n  6. Exit          ");

printf("\n--------------------");

printf("\n Enter your choise:");

scanf("%d",&ch);

if(ch==1)

{

printf("\n Enter the number:");

scanf("%d",&val);

insert(val);

}

else if(ch==2)

{

printf("\n");

display();

}

else if(ch==3)

{

printf("\n Enter value to delete:");

scanf("%d",&val);

delnode(val);

}

else if(ch==4)

{

printf("\n Enter the key:");

scanf("%d",&key);

printf("\n Enter the value:");

scanf("%d",&val);

insertaft(val,key);

}

else if(ch==5)

{

printf("\n Enter the key:");

scanf("%d",&key);

printf("\n Enter the value:");

scanf("%d",&val);

insertbfr(val,key);

}

else if(ch==6)

{

printf("\n good bye");

}

else

{

printf("\n enter invalid choice");

break;

}

}while(ch!=6);

getch();

}

No comments:

Post a Comment