Here is a menu driven program which performs all the operations on linked list as per the input given according to the menu.
C program for implementation of linked list and displaying elements of a linked list is as shown below:
C program for implementation of linked list and displaying elements of a linked list is as shown below:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node* ptr;
}node;
node *start=NULL, *temp, *p;
void create();
void display();
void insert_beg();
void insert_end();
void insert_sp();
void deletion();
void main(){
int choice;
clrscr();
SP:
printf(" **********MENU**********");
printf("\n1. create a node");
printf("\n2. Insert an element at the beginning of node");
printf("\n3. Display the status of the list");
printf("\n4. Insert at end of list");
printf("\n5. Insert at a specific point in list");
printf("\n6. Delete a node");
printf("\n7. Exit");
printf("\n\nEnter you choice:");
scanf(" %d",&choice);
switch(choice){
case 1: create(); break;
case 2: insert_beg(); break;
case 3: display(); break;
case 4: insert_end(); break;
case 5: insert_sp(); break;
case 6: deletion(); break;
case 7: exit(0);
default : printf("INVALID CHOICE! TRY AGAIN..\n\n");
}
goto SP;
}
void create(){
int i,item,num ;
printf("\nEnter the no. of nodes to be created:");
scanf(" %d",&num);
for(i=0;i<num;i++){
printf("Enter the data:");
scanf(" %d",&item);
temp=(node *)malloc(sizeof(node));
temp->data=item;
temp->ptr=NULL;
if(start==NULL)
start=temp;
else{
p=start;
while(p->ptr!=NULL)
p=p->ptr;
p->ptr=temp;
}
}
}
void display(){
temp=start;
printf("\nThe current status of the list is:");
while(temp!=NULL){
printf(" %d\t",temp->data);
temp=temp->ptr;
}
printf("\n\n");
}
void insert_beg(){
int new_item;
node *newb;
newb=(node *)malloc(sizeof(node));
printf("Enter data to be inserted:");
scanf(" %d",&new_item);
newb->data=new_item;
newb->ptr=start;
start=newb;
}
void insert_end(){
node *newe ;
int new_item;
newe=(node *)malloc(sizeof(node));
printf("\nEnter the element to be inserted:");
scanf("%d",&new_item);
newe->data=new_item;
newe->ptr=NULL;
temp=start;
while(temp!=NULL)
temp=temp->ptr;
temp->ptr=newe;
}
void insert_sp(){
node *newn;
int item,k,i;
printf("\nEnter the position where the node is to be inserted:");
scanf(" %d",&k);
newn=(node *)malloc(sizeof(node));
printf("\nEnter data: ");
scanf("%d",&item);
newn->data=item;
newn->ptr=NULL;
temp=start;
for(i=0;i<k-2;i++)
temp=temp->ptr;
newn->ptr=temp->ptr;
temp->ptr=newn;
}
void deletion(){
int k,i;
printf("\nEnter the position of the node which is to be deleted:");
scanf(" %d",&k);
temp=start;
for(i=1;i<k-1;i++)
temp=temp->ptr;
temp->ptr=temp->ptr->ptr;
}

No comments:
Post a Comment