9.stacks Unit-2
9.stacks Unit-2
Introduction
• Stack is an important data structure which stores its elements in
an ordered manner.
A B C D E
0 1 2 3 TOP = 4 5 6 7 8 9
A B C D E F
0 1 2 3 4 TOP =5 6 7 8 9
Pop Operation
• The pop operation is used to delete the topmost element from the
stack.
• However, before deleting the value, we must first check if TOP=-1,
because if this is the case then it means the stack is empty so no
more deletions can further be done.
• If an attempt is made to delete a value from a stack that is already
empty, an UNDERFLOW message is printed.
A B C D E
0 1 2 3 TOP = 4 5 6 7 8 9
A B C D
0 1 2 TOP = 3 4 5 6 7 8 9
Peek/Peep Operation
• Peek is an operation that returns the value of the topmost
element of the stack without deleting it from the stack.
• However, the peep operation first checks if the stack is empty or
contains some elements.
• If TOP = -1, then an appropriate message is printed else the value
is returned.
A B C D E
0 1 2 3 TOP = 4 5 6 7 8 9
1 7 3 4 2 6 5 X
TOP
Push Operation on a Linked Stack
Algorithm to PUSH an element in a linked stack
Step 1: Allocate memory for the new node and name it as New_Node
Step 2: SET New_Node->DATA = VAL
Step 3: IF TOP = NULL, then
SET New_Node->NEXT = NULL
SET TOP = New_Node
ELSE
SET New_node->NEXT = TOP
SET TOP = New_Node
[END OF IF]
Step 4: END
1 7 3 4 2 6 5 X
TOP
9 1 7 3 4 2 6 5 X
TOP
Pop Operation on a Linked Stack
Algorithm to POP an element from a stack
9 1 7 3 4 2 6 5 X
TOP
1 7 3 4 2 6 5 X
TOP
struct node {
int data;
struct node * next;
};
struct stack {
struct node *top;
};
int main(void) {
struct stack s; s.top=NULL;
int top_val;
push(&s,10);
---------
top_val = pop(&s);
}
void push(struct stack *ps, int n)
{
struct node *x;
x=(struct node *)malloc(sizeof(struct node))
if(x==NULL) {
printf(“Overflow”);
exit(1);
}
x->data = n;
x->next = ps->top;
ps->top = x;
}
int pop(struct stack *ps)
{
struct node *x; int value;
if(ps->top==NULL) {
printf(“Underflow”);
exit(1);
}
value = ps->top->data;
x=ps->top;
ps->top = ps->top->next;
free(x);
return value;
}
Multiple Stacks
• When we implemented a stack using an array, we had seen that
the size of the array must be known in advance.
• If the stack is allocated less space, then frequent OVERFLOW
conditions will be encountered.
• In case, we allocate a large amount of space for the stack, it will
result in sheer wastage of memory. Thus, there lies a tradeoff
between the frequency of overflows and the space allocated.
• So a better solution to deal with this problem is to have multiple
stacks or to have more than one stack in the same array of
sufficient size.
0 1 2 3 4 ………………………………. n-4 n-3 n-2 n-1
Stack A Stack B
Applications of Stacks
• Reversing a list
• Parentheses checker
• Recursion
• Tower of Hanoi