Singly Linked List – Creation LIFO
Program to create a LIFO Linked List:
Creation of a linked list may be done in LIFO order. If a linked list is created in LIFO order, then insertions as well as deletions are done at the same end i.e. the last node of the linked list is the first one to be deleted.
/*Program for linked list creation,insertion and deletion.*/
/*LIFO Linked List*/
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
struct list
{int n;
struct list *next;
}*head=NULL;
struct list *createnode()
{struct list *temp;
temp=(struct list*)malloc(sizeof(struct list));
return temp;
}
struct list *makenode(int x)
{struct list *temp;
temp=createnode();
temp->n=x;
temp->next=NULL;
return temp;
}
/*Insertion condition-At the end*/
/*New element is inserted at the end*/
void insertend(int x)
{
struct list *temp,*ptr=makenode(x);
if(head==NULL)
{head=ptr;
}
else
{temp=head;
while(temp->next!=NULL)
temp=temp->next;
temp->next=ptr;
}
}
/*Deletion condition-At the end*/
/*since last node is the first to be removed*/
void delnode()
{struct list *ptr,*temp;
if(head==NULL)
{printf(“List is empty!”);
return;
}
if(head->next==NULL)
{temp=head;
head=NULL;
free(temp);
return;
}
temp=head;
if(temp->next->next==NULL)
{ptr=temp->next;
temp->next=NULL;
free(ptr);
return;
}
while(temp->next->next!=NULL)
temp=temp->next;
ptr=temp->next;
temp->next=ptr->next;
free(ptr);
}
/*Displaying list*/
void displaylist()
{
struct list *temp;
if(head==NULL)
{printf(“nList is empty.”);
return;
}
temp=head;
while(temp!=NULL)
{printf(“%d->”,temp->n);
temp=temp->next;
}
printf(“bb “);
}
void main()
{
int ch,num;
while(1)
{
clrscr();
printf(“nLinked List (LIFO)-Menu”);
printf(“nn1. Insert”);
printf(“n2. Delete”);
printf(“n3. Display”);
printf(“n4. Exit”);
printf(“nnEnter your choice?”);
scanf(“%d”,&ch);
switch(ch)
{
case 1: printf(“nEnter any number?”);
scanf(“%d”,&num);
insertend(num);
break;
case 2:
delnode();
break;
case 3:
displaylist();
break;
case 4:
exit(0);
default:
printf(“Invalid choice!”);
}
getch();
}
}