Computer Science

  • -

Computer Science

Category : Project Work

A Sample Link List C Program

 

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define null 0

typedef struct Node
{
int data;
struct Node *link;
}
Node;

Node *Head=null;
Node *getnode()
{
Node *temp;
temp=(Node *)malloc(sizeof(Node));
temp->link=null;
return temp;
}

void insert_at_front()
{
int x;
Node *newnode;
printf(“\nEnter data: “);
scanf(“%d”,&x);
newnode=getnode();
newnode->data=x;
newnode->link=Head;
Head=newnode;
}

void insert_after_y()
{
int x,y;
Node *newnode,*temp;
printf(“\nAfter which do you want to insert? “);
scanf(“%d”,&y);
temp=Head;
while(temp!=null && temp ->data!=y)
{
temp=temp->link;
}
if(temp==null)
{
printf(“\nNode not present.\n”);
return;
}
printf(“\nEnter data: “);
scanf(“%d”,&x);
newnode=getnode();
newnode->data=x;
newnode->link=temp->link;
temp->link=newnode;
return;
}

void delete_front()
{
Node *temp=Head;
if(Head==null)
{
printf(“\nList is empty.\n”);
return;
}
Head=Head->link;
free(temp);
return;
}

void delete_x()
{
int x;
Node *temp1,*temp;
printf(“\nWhich node do you want to delete? “);
scanf(“%d”,&x);
temp=Head;
while(temp!=null && temp->data!=x)
{
temp1=temp;
temp=temp->link;
}
if(temp==null)
{
printf(“\nNode not present.\n”);
return;
}
temp1->link=temp->link;
free(temp);
return;
}

int display_menu()
{
int choice;
printf(“\n\t\aMENU :-\n”);
printf(“\n1. Create linear list.”);
printf(“\n2. Insert at Front.”);
printf(“\n3. Insert after node y.”);
printf(“\n4. Delete Front.”);
printf(“\n5. Delete node x.”);
printf(“\n0. Exit.”);
printf(“\n\nEnter your choice: “);
scanf(“%d”,&choice);
return(choice);
}

void display_list()
{
Node *temp=Head;
printf(“\nPresent list: “);
while(temp!=null)
{
printf(“\t%d”,temp->data);
temp=temp->link;
}
}

void main()
{
int choice;
do
{
choice=display_menu();
switch(choice)
{
case 1:
case 2:
insert_at_front();
break;
case 3:
insert_after_y();
break;
case 4:
delete_front();
break;
case 5:
delete_x();
break;
case 0:
exit(0);
default:
printf(“\nWrong choice.Give choice again.”);
}
display_list();
}
while(choice);
return;
}


Class-XI Annual Practical Examination 2017View Routine