You are on page 1of 4

/* Array implementation of Linked List */ #include<stdio.h> #include<conio.h> #include<stdlib.

h> #define MAX 100 #define null -1 struct linked { int info, link; }; struct linked list[MAX]; int start=null, avail = 0; void ins(int num); void del(int x); void trav(); int main() { int i, num, choice; for(i=0;i<MAX-1;++i) list[i].link = i+1; list[i].link = null; printf("As per your choice press a number when prompted to do so"); printf("\n1. Insert a new node"); printf("\n2. Delete a node\n"); printf("3. Traverse the list and display each element"); printf("\n4. Exit\n"); while(1) { printf("What would you like to do?\n"); scanf("%d", &choice); switch(choice) { case 1: printf("\nEnter the value to be inserted\n"); scanf("%d", &num); ins(num); break; case 2: printf("\nWhat should be the number in the node to be deleted?\n"); scanf("%d", &num); del(num); break; case 3: printf("\nThe list is as follows :"); trav(); break; case 4: printf("\nThe final list is :"); trav(); printf("\n\n\t\t\tSee You Later!!"); getch(); exit(0); default: printf("\nPress 1,2,3 or 4 only"); } printf("\n\n"); } return(0); }

void ins(int num) { int temp, tmp; if(avail == null) { printf("\nOVERFLOW"); getch(); exit(1); } temp = avail; avail = list[avail].link; list[temp].info = num; list[temp].link = null; if(start == null) { start = temp; } else if(num < list[start].info) { list[temp].link = start; start =temp; } else { tmp = start; while(list[tmp].link != null && num >= list[list[tmp].link].info) { tmp = list[tmp].link; } list[temp].link = list[tmp].link; list[tmp].link = temp; } } void del(int x) { int curr, prev; curr = start; prev = null; if(start == null) { printf("\nUNDERFLOW. List is empty\n"); return; } while(curr!= null && list[curr].info != x) { prev = curr; curr = list[curr].link; } if(curr == null) { printf("\nThe required node is not present in the list\n"); return; } if(prev == null) { start = list[start].link; list[curr].link = avail; avail = curr; } else { list[prev].link = list[curr].link;

list[curr].link = avail; avail = curr; } printf("\nAfter deletion, the list is:"); trav(); } void trav() { int temp; printf("\n"); if(start == null) { printf("Empty List"); return; } temp = start; while(temp != null) { printf("%d ", list[temp].info); temp = list[temp].link; } }

Output

You might also like