Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

LINKED LIST AND OPERATIONS ON IT

#include<stdio.h> #include<stdlib.h> struct node*create(); void display(struct node*); struct node*insert(struct node*); struct node*delete(struct node*); int count(struct node*); struct node { int data; struct node*link; }; void main() { struct node*a; int i=1,n; clrscr(); printf("\n creating the linked list\n "); a=create(); display(a); do { printf("\n enter the choice"); printf("\n 0.exit\n1.insertion\n2.deletion\n3.count"); scanf("%d",&i); switch(i) { case 1: a=insert(a); display(a); break; case 2: a=delete(a); display(a); break; case 3: n=count(a); printf("\nthe number of nodes or items are\t%d",n); break; } } while(i!=0); }; struct node*create() { int c,item; struct node*p,*temp,*head; head=(struct node*)malloc(sizeof(struct node));

p=head; do { printf("\nenter data,-999 for end\t"); scanf("%d",&item); if(item==-999) { p=head; head=head->link; return head; } else { temp=(struct node*)malloc(sizeof(struct node)); temp->data=item; temp->link=NULL; p->link=temp; p=temp; } }while(1); }struct node*insert(s) struct node*s; { struct node*x,*a; int n,item,i; printf("\nenter the position of insertion\t"); scanf("%d",&n); printf("\nenter the data item\t"); scanf("%d",&item); a=(struct node*)malloc(sizeof(struct node)); a->data=item; if(n==0) { a->link=s; s=a; } else { x=s; for(i=1;i<n;i++) { x=x->link; } a->link=x->link; x->link=a; } return s; } struct node*delete(s) struct node*s; { struct node*a,*x;

int n,i; printf("\n enter the position of deletion \t"); scanf("%d",&n); if(n==1) {a=s; s=s->link; free(a); } else { x=s; for(i=1;i<n-1;i++) { x=x->link; } a=x->link; x->link=a->link; } return s; } int count(s) struct node*s; { int c=0; while(s!=NULL) { s=s->link; c=c+1; } return c; } void display(s) struct node*s; { printf("\nthe linked list is\n"); while(s!=NULL) { printf("%d\t",s->data); s=s->link; } getch(); } OUTPUT: Creating the linked list Enter data,-999 for end 1 Enter data,-999 for end 2 Enter data,-999 for end 4 Enter data,-999 for end 3 Enter data,-999 for end 5

Enter data,-999 for end 6 Enter data,-999 for end -999 The linked list is 124356 Enter the choice 0.exit 1.insertion 2.deletion 3.count 1 Enter the position of insertion 2 Enter the data item 3 The linked list is 12 3 4 3 5 6 Enter the choice 0.exit 1.insertion 2.deletion 3.count 2 Enter the position of deletion 3 The linked list is 123356 Enter the choice 0.exit 1.insertion 2.deletion 3.count 3 The number of nodes or items are 6 Enter the choice 0.exit 1.insertion 2.deletion 3.count 0

You might also like