Chapter -5- Stacks (3)
Chapter -5- Stacks (3)
2
Stack
It is a data structure that has access to its
data only at the end or top of the list.
It operates on LIFO (last in first out) basis.
Stack uses a single pointer or (index) to keep
track of the information or data on the
stack.
It has two basic operations:
▪ Push: inserting or adding data at the top
of the stack,
▪ Pop: removing data from the top of the
stack.
3
…
A stack of
coins
4
…
5
…
Push Pop
Push(5) Pop 15
……………….. Push (6) 9 12
Push(7)
………………. Push (9) 6 7
Push(12) 6
5 Push(15) 5
12
pop 7
6
5
6
Array implementation of push and pop operation
▪ Analysis:
suppose the stack has the following structure.
int num[max-size];
We need to have an integer variable that stores an index value that tells
us:
▪ The position where to store a new value
▪ The total number of elements stored in the stack
int top =-1;
7
To push/add an element to the stack
Check if there is enough space in the stack
▪ To add new value we should have to check the space left
▪ top<max_size-1?
❑Yes – increment top , store the element in num[top]
8
To pop or remove an element from the stack
check if there is data in the stack
top>=0?
▪ Yes: - copy/remove data at num[top], decrement top
▪ No: - stack underflow
9
Implementation – push
int num[max_size];
int top=-1;
void push(int x)
{
if (top<max_size-1)
{
top++;
num[top]=x;
}
else
cout<<“stack overflow”;
}
10
Implementation - pop
int pop()
{
int x;
if(top>=0)
{
x=num[top];
top --;
}
else
Cout<<“stack underflow”’;
return x;
}
11
Implementation
Size of stack
int sizeofstack()
{
return(top+1)
}
Is empty?
Bool isempty()
{
return (top==-1)
}
Is full?
Bool isFull()
{
Return(top==max_size – 1)
}
12
Linked List Implementation of Push and Pop operations
When we implement stack using array :
We create an array of predefined size & we cannot increase the size of the array
if we have more elements to insert.
If we create a very large array, we will be wasting a lot of memory space.
So to solve this lets try to implement Stack using Linked list where we will
dynamically increase the size of the stack as per the requirement.
Taking this as the basic structure of our Node:
struct number
{
int num;
number *next;
};
13
Linked List Implementation of Push and Pop operations
Definition
struct number
{
int num;
number *next; Botptr
};
Topptr
14
Analysis:
▪ We need two pointers (Botptr and topptr) that points to first and last node of the stack
number *botptr=NULL, *topptr=NULL;
▪ To push data to the stack
Check if there is enough space in the stack – i.e free memory space. We need a pointer
that points to the newly created -
newnumptr = new number;
newnumptr !=NULL→ there is free Memory space pointed by newnumptr
Yes: - copy/store the pushed value to newly created node
Create the link between the last node and the new node….
void push(int value)
{
number*ptr = new number(); Inserting first
ptr->data = value;
ptr->next = top;
top = ptr;
} 15
(Continued)…
Make topptr to point to the last node (newly created node) → cin>>newnumptr-
>num; newnumptr->next=NULL;
NO: stack overflow
Botptr
newnumptr
Topptr
16
POP
▪ Check if there is data in the stack
bottomptr!=NULL???
Yes: - topptr should point to the previous node. When we have only one node
botptr and topptr should point to NULL
Deleting the last node
No: - stack underflow
prevptr
botptr lastptr
17
Exercise
• Write the complete code of stack implementation using single linked list
and array.
18
Application of Stack
1. Undo mechanism for text editor
2. Reverse string
3. Check the balance of parenthesis {}/Compiler Syntax Analyzer
4. Infix to postfix/prefix conversion(expression)
5. Postfix Notation and prefix Notation
19
Application of Stack
➢There are three notations to represent an arithmetic expression:
Infix Notation
Example: A + B, (C - D) etc.
➢All these expressions are in infix notation because the operator comes between the
operands
Prefix Notation
➢Example: + A B, -CD etc.
➢All these expressions are in prefix notation because the operator comes before the
operands.
Postfix Notation
Example: AB +, CD+, etc.
➢All these expressions are in postfix notation because the operator comes after the
operands.
20
Application of Stack
Infix to postfix conversion, infix to prefix conversion;
Its mandatory considered precedence and associativity rule
Priority of precedence
1. (),{},[],
2. ^ power
3. *, /
4. + ,-
Associativity rule
1. power------------right to left;
2. *,/,-.+--------------------------left to right
Example A. 5+1*6--------? B. 1+2*5+30/5 ?
21
Application of Stack
Infix to postfix conversion
Rule
1. Print operand as they arrive
2. If stack is empty or contains left parenthesis on the top push the incoming
operator onto the stack
3. If incoming symbol is ‘(’ push into the stack
4. If incoming symbol is ‘)’pop the stack and print the operator until parenthesis
found.
5. If the incoming symbol is highest precedence than the top of the stack ,push it on
the stack
6. If the incoming symbol is lower precedence than the top of the stack, pop and
print the top, then test the incoming operator against the new top of the stack
22
Application of Stack
Infix to postfix conversion
Rule
7. If incoming operator has equal precedence with the top of the stack use
associativity rule
A. if associativity left to right then pop and print the top of the stack then push the
incoming operator
B. if associativity right to left then push the incoming operator
8. At the end of the expression pop and print all operator of stack
Example Infix Postfix
(A+B)/C ?
(A*B) + (D-C) ?
K+L-M*N+O*W/U/V*T+Q
23
Application of Stack
Infix to prefix conversion
Rule
1. First reverse the expression
2. Print operand as they arrive
3. If stack is empty or contains left parenthesis on the top push the incoming
operator onto the stack
4. If incoming symbol is ‘)’ push into the stack
5. If incoming symbol is ‘(’pop the stack and print the operator until parenthesis
found.
6. If the incoming symbol is highest precedence than the top of the stack ,push it on
the stack
7. If the incoming symbol is lower precedence than the top of the stack, pop and
print the top, then test the incoming operator against the new top of the stack
24
Application of Stack
Infix to prefix conversion
Rule
7. If incoming operator has equal precedence with the top of the stack use
associativity rule
A. if associativity left to right then push the incoming operator onto stack
B. if associativity right to left then push the incoming operator
8. At the end of the expression pop and print all operator of stack
9. Finally reverse the output
Example Infix prefix
(A+B)/C ?
(A*B) + (D-C) ?
K+L-M*N+(O˄P)*W/U/V*T+Q
25
Application of Stack
5. Computing Postfix Notation(Postfix Evaluation)
Scan from left to right , and put operand to stack.
• Before evaluating the postfix evaluation, the following conditions must be checked.
If any one of the conditions fails, the postfix evaluation is invalid.
➢When an operator encounters the scanning process, the Stack must contain a pair
of operands or intermediate results previously calculated.
➢When an evaluation has been completely evaluated, the Stack must contain exactly
one value. Op=pop()
+
Op1=pop()
AB+ B
Op2=pop()
A
Op2 op op1 = result
Result
Push (result) 26
…
example
AB+C*
+ *
B C
A Result1 Result1 Result2
27
…
1. Consider the following stack implemented using stack. #define SIZE 11
struct STACK {
int arr [SIZE];
int top=-1;}
What would be the maximum value of the top that does not cause the overflow of the stack?
A. 8 B. 9 C. 11 D. 10
2. Which of the following is not the application of stack?
A. parenthesis balancing program
B. Tracking of local variables at run time
C. Compiler Syntax Analyzer
D. Data Transfer between two asynchronous processes
28
…
3. in a stack, if a user tries to remove an element from an empty stack it is
called __
a) Underflow
b) Empty collection
c) Overflow
d) Garbage Collection
4. Here is an infix expression: 4 + 3*(6*3-12). Suppose that we are using the
usual stack algorithm to convert the expression from infix to postfix notation.
The maximum number of symbols that will appear on the stack AT ONE
TIME during the conversion of this expression?
A. 1 B. 2 C. 3 D. 4
5. What is the value of the postfix expression 6 3 2 4 + – *?
A. 1 B. 40 C. 74 D. -18 E. 18
29