#include<stdio.h> #include<stdlib.h> #include<conio.h> struct node { int data; struct node *link; }; struct node *front = NULL , *read = NULL ; void create(void); void append(void); void addFirst(void); void addAfter(void); void deleteNode(void); int length(void); void display(void); void main() { int ch , len ; while(1) { printf(“\n/**Single linked list Operations**/\n”); printf(“1.Create \n”); printf(“2.Append \n”); printf(“3.AddFirst \n”); printf(“4.AddAfter \n”); printf(“5.Delete Node \n”); printf(“6.Display \n”); printf(“7.Length \n”); printf(“8.Quit \n”); printf(“Enter Choice : “); scanf(“%d”, &ch); switch(ch) { case 1 : create(); break; case 2 : append(); break; case 3 : addFirst(); break; case 4 : addAfter(); break; case 5 : deleteNode(); break; case 6 : display(); break; case 7 : len = length(); printf(“Length : %d \n\n”, len); break; case 8 : exit(0); default : printf(“Invalid choice….\n\n”); } } } void create() { struct node *temp,*p; temp = root ; while(1) { p=(struct node *)malloc(sizeof(struct node)); printf(“Enter data :”); scanf(“%d”, &p->data); if(root==NULL) { root = p; p->link = NULL; temp = p; } else { temp->link=p; temp=p; } printf(“Do you want to stop(y/n) : “); if(getch()==’y’) { break; } p->link=NULL; } } void append() { struct node *temp,*p; temp = root; p=(struct node *)malloc(sizeof(struct node)); printf(“Enter the data : “); scanf(“%d”, &p->data); p->link = NULL ; if(root == NULL) root = p ; else { while(temp->link != NULL) { temp = temp->link; } temp->link = p; p->link = NULL; } } void addFirst() { struct node *p; p=(struct node *)malloc(sizeof(struct node)); printf(“Enter data : “); scanf(“%d”, &p->data); p->link = root; root = p; } void addAfter() { struct node *temp,*p,*q; int loc, i=1; temp = root ; printf(“Enter location to insert :”); scanf(“%d”, &loc); if(loc>length()) { printf(“Invalid location to insert\n\n”); } else { while((i<loc)) { temp=temp->link ; i++ ; } p=(struct node *)malloc(sizeof(struct node)); printf(“Enter data : “); scanf(“%d”,&p->data); q = temp->link; temp->link = p; p->link = q; } } void display() { if(root == NULL) { printf(“List is empty\n\n”); } else { struct node* temp = root ; while(temp != NULL) { printf(“%d \n”, temp->data); temp = temp->link ; } } } int length() { struct node* temp=root ; int count = 0; while(temp != NULL) { count++ ; temp = temp->link ; } return count ; } void deleteNode() { struct node *temp, *p; int i=1,loc; temp = root ; printf(“Enter loc to delete : “); scanf(“%d”,&loc); if(loc>length()) printf(“Invalid location to delete\n\n”); if(loc==1) { printf(“Deleted item : %d \n”, temp->data); root = temp->link ; temp->link = NULL ; free(temp); } else { while(i<loc-1) { temp = temp->link; i++; } p = temp->link; printf(“Deleted item : %d \n”, p->data); temp->link = p->link; p->link = NULL ; free(p); } } |