🤔Basically What is Stack and Singly Linked List?
⭕ Stack: A stack is a linear data structure in which all the insertion(Push) and deletion(Pop) of data or you can say its values are done at one end only, rather than in the middle.
Read more >> About stack
⭕ Singly Linked List: A Linked list is a linear data structure in which collection of data elements whose order is not given by their physical placement in memory. Instead, each element points to the next.
⇨ In the Linked list Nodes are allocated Dynamically. [ Each node contains Data(information) part & Link(reference) part ]
⇨ Link part of each node points to its next node.
👨💻 Write a program to Implement stack using a singly linked list.
CODE:
//in short make functions 1. insert last (Like push Operation in the stack) and 2. delete last (Like pop Operation in the stack)
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *head=NULL;//*last=NULL;
void insert_first();
void delete_last();
void display();
int op_list();
main()
{
int choice=op_list();
while(choice!=4)
{
switch(choice)
{
case 1:{insert_first();}break;
case 2:{delete_last();}break;
case 3:{display();}break;
case 4:{exit(0);}break;
default:{printf("Please!!! ,Enter the between 1 to 4 ");}break;
}
choice=op_list();
}
}
void insert_first()
{
int x;
struct node *p,*temp;
p=(struct node *)malloc(sizeof(struct node));
if(p==NULL)
{
printf("Unable to allocate memory !! Please try again !!");
}
else
{
p->link=NULL;
if(head==NULL)
{
head=p;
printf("Enter data:");
scanf("%d",&x);
p->data=x;
}
else
{
for(temp=head;temp->link!=NULL;temp=temp->link)
{
}
printf("test pass");
temp->link=p;
printf("Enter data:");
scanf("%d",&x);
p->data=x;
}
}
}
void delete_last()
{
struct node *temp;
if(head==NULL)
{
printf("\nStack is EMPTY !!!");
}
else
{
if(head->link==NULL)
{
head=NULL;
}
else
{
for(temp=head;temp->link->link!=NULL;temp=temp->link)
{
}
free(temp->link);
temp->link=NULL;
}
}
}
void display()
{
struct node *temp;
if(head==NULL)
{
printf("\nStack is EMPTY !!!\n");
}
else
{
printf("\n");
for(temp=head;temp!=NULL;temp=temp->link)
{
printf("| %d |\n",temp->data);
}
}
}
int op_list()
{
int choice;
printf("\n->List of Operations\n1.Push\n2.Pop\n3.Display Stack\n4.Exit\n-->Which operation you want to perform :");
scanf("%d",&choice);
return choice;
}
OUTPUT:
Comments
Post a Comment