You are on page 1of 4

najar

//singly linked list in C //Najar Aryal //BCT //Kathmandu Engineering COllege //aryalnz@gmail.com #include<stdio.h> #include<conio.h> #include<stdlib.h> struct list { int data; struct list *next; }; struct list *init=(list*)malloc(sizeof(list*)); struct list *temp=(list*)malloc(sizeof(list*)); void start() { init->data=NULL; init->next=NULL; } void add_end(int d) { struct list *new1=(list*)malloc(sizeof(list*)); temp=init; while(temp->next!=NULL) {temp=temp->next;} new1->data=d; new1->next=NULL; temp->next=new1; } void add_beg(int d) { struct list *new1=(list*)malloc(sizeof(list*)); temp=init; new1->data=d; new1->next=temp->next; temp->next=new1; } void add_mid(int p , int d) {

najar

struct list *new1=(list*)malloc(sizeof(list*)); temp=init->next; while(temp->data!=p) { temp=temp->next; if(temp->next==NULL && temp->data!=p) { printf("\n INVALID DATA");return;} } new1->data=d; new1->next=temp->next; temp->next=new1; } void del_end() { temp=init; struct list *temp1; while(temp->next!=NULL) { temp1=temp; temp=temp->next; } temp1->next=NULL; } void del_beg() { temp=init; if(temp->next->next!=NULL) init->next=temp->next->next; else temp->next=NULL; } void del_mid(int p) { int flag=0; temp=init; struct list *temp1=temp; while(temp->data!=p && temp->next!=NULL) { temp1=temp; temp=temp->next; if(temp->data==p) {flag=1;} }

najar

if(flag==0) {printf("SORRY INVALID DATA!!!!");return;} temp1->next=temp->next; } void view() { int n=1; struct list *temp2; temp2=init->next; while(temp2!=NULL) { printf("\n node %d. has %d",n,temp2->data); n++; temp2=temp2->next; } } void main() { int n,d,i,p,j; start(); do { clrscr(); printf("\n Enter choice \n1.Add \n2.delete\n3.view \n4.exit\n"); scanf("%d",&n); switch(n) { case 1:printf("\nEnter data to be added"); scanf("%d",&d); printf("\n where to add \n\t\t1.Beg\n\t\t2.After some node \n\t\t3.End"); scanf("%d",&i); switch(i) { case 3: add_end(d);break; case 2:printf("\n After which node(enter data)"); scanf("%d",&p); add_mid(p,d);break; case 1: add_beg(d);break; }view(); break;

najar

case 2: printf("\n delete from \n\t\t1.Beg\n\t\t2.middle\n\t\t3.End"); scanf("%d",&j); switch(j) { case 3:del_end();break; case 2:printf("\nenter data to delete"); scanf("%d",&p); del_mid(p);break; case 1:del_beg();break; } view();break; case 3:view();getch();break; case 4: exit(0); } printf("\n\nANY KEY TO CONTINUE........"); getch(); }while(1); }

You might also like