Stack
Stack
STACK
STACK
• A Stack is a linear data structure that holds a linear, ordered sequence
of elements.
Overflow
Underflow
Advantages of stack
• Easy implementation
• Supports backtracking
• No random access
• Memory management
• Call logs, E-mails, and Google photos in any gallery are also stored in
form of a stack.
Applications of stack in data structure
• Function calls and recursion
• Undo/Redo operations
• Expression evaluation
• Balanced Parentheses
• Backtracking Algorithms
Two ways to implement stack
Static -
Array Based Implementation
Dynamic
Linked list Based Implementation
Quizzzzz
1. In a sequence of operations – push(1), push(2), pop(),push(1),
push(2), pop(), pop(), pop(),push(2), pop() are performed on a
stack, the sequence of popped out values are:
a) 2,2,1,2,2
b) 2,1,2,1,2
c) 2,2,1,1,2
d) 2,1,2,2,1
2. Consider the following operations performed on a stack of size 5:
push(a) , pop(), push(b),push(c), pop(), push(d), pop(), pop(), push(e).
a) Underflow occurs
b) Overflow Occurs
int stack[N];
int top=-1;
int main() case 2:
{ pop();
int choice; break;
clrscr();
case 3:
while(choice!=5)
display();
{
break;
printf("\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT");
printf("\nEnter your choice: "); case 4:
scanf("%d",&choice); exit(0);
switch(choice) default:
{ printf("wrong choice");
case 1: }
push(); getch();
break;
}
}
Push function
void push()
{
int x;
printf("\n Enter data: ");
scanf("%d",&x);
if(top==N-1)
{
printf("stack overflow");
}
else
{
top=top+1;
stack[top]=x;
}
}
Pop function
void pop()
{
int item;
if(top==-1)
{
printf("\n Stack Underflow");
}
else
{
item=stack[top];
top=top-1;
printf("The deleted Item is %d",item);
}
}
Peek function
void peek()
{
if(top==-1)
{
printf("\n Stack Underflow");
}
else
{
printf("The top most element is %d",stack[top]);
}
}
Display Function
void display()
{
int i;
if(top==-1)
{
printf("Stack is Empty");
}
else
{
for(i=top;i>=0;i--)
{
printf("%d\n",stack[i]);
}
}
}