Stack Operations using ‘c’
A stack is a direct information structure that follows the Rearward In-First-Out (LIFO) guideline. Components are embedded and taken out from a similar end, known as the highest point of the stack. Here are the essential tasks performed on a stack:
1. Push: Adds a component to the highest point of the stack. The new component turns into the most as of late added thing.
2. Pop: Eliminates and returns the component from the highest point of the stack. The component that was added last is taken out, and the top pointer is moved to the following component in the stack.
3. Look/Top: Returns the component at the highest point of the stack without eliminating it. It permits you to analyze the highest component in the stack.
4. IsEmpty: Checks regardless of whether the stack is unfilled. It returns valid assuming that the stack is unfilled and bogus in any case.
These tasks empower the control and recovery of components in a stack. This is an illustration of the way these tasks can be performed on a stack:
Beginning stack: [ ]
1. Push 1: [1]
2. Push 2: [1, 2]
3. Push 3: [1, 2, 3]
4. Pop: [1, 2]
5. Look: 2
6. Pop: [1]
7. IsEmpty? Misleading
8. Pop: [ ]
9. IsEmpty? Valid
Like lines, stacks can have varieties and various executions, like utilizing exhibits or connected records. Extra activities like size/count or clearing the stack might be upheld in some stack executions.
It's significant that the stack activities can be utilized to execute different calculations and take care of explicit issues, for example, articulation assessment, capability call the board, backtracking, and that's just the beginning.
Program:-
#include
<stdio.h>
#include
<stdlib.h>
struct node
{
int data;
struct node*next;
}*head;
int main()
{
int data,n,i,ch;
printf("enter no of keys in the
stack");
scanf("%d",&n);
printf("1.push 2.pop
3.show 4.exit");
for(i=0;i<n;i++)
{
printf("enter your choice");
scanf("%d",&ch);
switch(ch)
{
case 1:push();
break;
case 2:pop();
break;
case 3:display();
break;
case 4:
printf("exiting");
break;
}
}
return 0;
}
void push()
{
int val;
struct node *ptr;
ptr=(struct node*)malloc(sizeof(struct
node));
printf("enter the value");
scanf("%d",&val);
if(head==NULL)
{
ptr->data=val;
ptr->next=NULL;
head=ptr;
}
else
{
ptr->data=val;
ptr->next=head;
head=ptr;
}
}
void pop()
{
int item;
struct node*ptr;
if(head==NULL)
{
printf("underflow");
}
else
{
item=head->data;
ptr=head;
head=head->next;
free(ptr);
printf("item poped %d",item);
}
}
void
display()
{
int i;
struct node*ptr;
ptr=head;
if(ptr==NULL)
{
printf("stack is empty");
}
else
{
while(ptr!=NULL)
{
printf("%d",ptr->data);
ptr=ptr->next;
}
}
}
Output:-
0 Comments