Unit 2: Stack
By:Dabbal Singh Mahara
Amrit Campus
1
Tribhuvan University
BSc CSIT 3rd Semester
Data Structures and Algorithms (CSC211)
2.
2
What is aStack?
• A stack is an ordered collection of elements in which
insertion and deletion take place only at one end, called the
top of the stack.
• The last element inserted into the stack is the first one to be
removed.
• The stack is a linear data structure that follows the LIFO
(Last In, First Out) principle.
• The Insertion operation is referred to as Push and deletion
operation is called Pop.
Basic Operations onStack
• push(x) → Insert element x on the top
• pop() → Remove the element from the top
• peek() / top() → View the top element without removing it
• isEmpty() → Check if stack is empty
• isFull() → Check if stack is full (for fixed-size stacks)
5
The Stack ADT
•A Stack ADT is an abstract data type that defines a collection of elements with
operations based on the Last-In, First-Out (LIFO) principle.
• It specifies what operations can be performed on the stack, without describing
how the stack is implemented internally.
• A typical Stack ADT supports the following operations:
1. CreateEmptyStack(S): Create or make stack S be an empty stack
2. Push(S, x): Insert x at one end of the stack, called its top
3. Top(S): If stack S is not empty; then retrieve the element at its top
4. Pop(S): If stack S is not empty; then delete the element at its top
5. IsFull(S): Determine if S is full or not. Return true if S is full stack; return
false otherwise
6. IsEmpty(S): Determine if S is empty or not. Return true if S is an empty
stack; return false otherwise. 7
8.
Applications of Stack
Stackis used directly and indirectly in the following fields:
8
• Function calls: The call stack stores return addresses during nested or recursive
function execution.
• Expression evaluation: A stack evaluates postfix expressions by pushing
operands and popping for operations.
• Expression conversion: Infix-to-postfix conversion uses a stack to manage
operators and precedence.
• Backtracking: Maze-solving algorithms use stacks to remember previous
positions.
• Undo/redo: Text editors use stacks to track previous editing actions.
• DFS traversal: Depth-First Search uses a stack to explore nodes.
• Browser navigation: The back button uses a stack to store visited pages.
9.
Array Implementation ofStack
• In the array implementation, a stack is represented using a fixed-
size array and an integer variable called top that indicates the index
of the topmost element.
#define MAX 100
struct Stack {
int data[MAX];
int top;
} ;
• data[MAX] → Array to store stack elements
• top → Index of the top element in the stack
• Initially, we set top = -1;
9
10.
Stack Underflow andOverflow
Stack Underflow
• Stack underflow is the situation when the stack contains no element.
• At this point the top of stack is present at the bottom of the stack.
• In array implementation of stack, conventionally top=-1 indicates the
empty.
Stack Overflow
• It is the situation when the stack becomes full, and no more elements
can be pushed onto the stack.
• At this point the stack top is present at the highest location (MAX - 1)
of the stack.
10
11.
push operation onStack
• Push operations inserts a new data item into the stack.
• Let Data[MAX] be an array to implement the stack having capacity of MAX.
• The variable top denotes the top of the stack.
• Algorithm;
1. [check stack overflow condition]
if top == MAX-1 then
print “Stack is full.” and Exit
else
top = top+1
Data[top] = item
2. Exit 11
12.
• POP operationdeletes the top element of the stack and assign it to a
variable item
• Algorithm:
1.[Check Stack Underflow]
If top == -1 then
Print “Stack is empty” and Exit
else
item=Data [top]
top = top-1
Return the deleted element
2. Exit
12
POP operation on Stack
13.
Push() function
void push(Stack*s, int x) {
if (top==MAX-1) {
printf("Stack Overflow! Cannot push %dn", x);
}
else {
++ s -> top;
s -> data[top] = x;
printf("%d pushed to stack.n", x);
}
}
}
13
14.
Pop() function
void pop(Stack*s) {
int x;
if (s->top == -1) {
printf("Stack is empty.”);
}
else {
x = s -> data[s->top];
-- s -> top;
printf(“nPopped Item: %d", x);
}
}
}
14
15.
Lab 2
Write amenu-driven program in C to perform the following
operations on a stack implemented in array.
1. PUSH
2. POP
3. PEEK
4. DISPLAY
5. EXIT
15
16.
The Infix, Postfixand Prefix Notations
Arithmetic expression:
An expression is defined as a number of operands or data items
combined using several operators. There are basically three types of
notations for an expression;
1) Infix notation 2) Prefix notation 3) Postfix notation
Infix notation:
In infix notation, the operator is written between the operands.
Example:
A + B
(A + B) * C
• It is most common in arithmetic expressions used by humans.
• It requires parentheses and precedence rules to avoid ambiguity. 16
17.
The Infix, Prefix,Postfix Notation
Prefix Notation:
• In prefix notation, the operator is written before the operands.
• Example: + A B
* + A B C
• No need for parentheses because the order of evaluation is unambiguous.
• Used mostly in computer languages and expression evaluation.
Postfix Notation:
• In postfix notation, the operator is written after the operands.
• Example: A B +
A B + C *
• No parentheses required.
• Postfix expressions are easy to evaluate using a stack, making it efficient for compilers
and calculators. 17
18.
Why Use Prefixand Postfix Expressions?
1. Eliminates the Need for Parentheses
Infix expressions often require parentheses to clarify the order of operations. Prefix and
postfix notations make the order explicit, removing any ambiguity.
2. Simplifies Computation Using Stacks
These notations can be evaluated efficiently by computers using a stack, enabling
straightforward, single-pass computation without dealing with operator precedence rules.
3. Unambiguous and Compiler-Friendly
Prefix and postfix expressions provide a clear and unambiguous representation, making
them ideal for compilers and calculators to parse and evaluate expressions reliably.
18
19.
Infix to PostfixConversion
Algorithm:
Let P be a valid infix expression , Q be an empty postfix expression , Opstack be an empty
operator stack.
1. Repeat steps 2 to 6, until end of string, P.
2. Scan one char at a time from left to right in P.
3. If scan char is '(', then push it into Opstack.
4. If scan char is operand, then append it to Postfix String Q.
5. If scan char is operator, then,
a. while(Opstack is not empty and precedence(Opstack_Top) >= precedence(scan char))
i. Pop the Opstack and append it to Postfix String Q.
b. Push the scan operator to Opstack.
6. If scan char is ')' then Pop Opstack and append to Postfix String, unitl '(' is encountered. Ignore
both '(' and ')'.
7. while( Opstack is not empty ) Pop Opstack and append to Postfix String.
8. End.
19
20.
• Convert followinginfix expression into postfix expression:
a + b * c + ( d * e + f ) * g
Solution,
• Scan one character at time from the input string until end of the input
• Create an empty stack 'Opstack' to hold operators and output string Q
to hold output postfix expression.
Example: infix to postfix conversion
Postfix String: Q
Opstack
20
21.
Input String: a+ b * c + ( d * e + f ) * g
• Let us start scanning the input string
• Read first symbol a, since it is operand, pass it to the poststring Q.
• Read next symbol '+' and pushed into stack.
• Read next symbol b and append it to Q.
• Read next symbol i.e. * , check precedence of stack top and scan
char push * into the stack.
• Read c from input string and append it to Q.
• Read next symbol +, check precedence with stack operators, we find that
* has higher precedence so pop * and append it to Q. Again check for next stack
symbol + which is of equal precedence with scan +, therefore, pop it and append to
the Q. Finally push scan + into the stack.
Example: infix to postfix conversion
*
+
Opstack
PostString Q: a b
PostString Q: a
PostString Q: a b c
PostString Q: a b c * +
+
Opstack
21
22.
Input string: a+ b * c + ( d * e + f ) * g
• Next symbol scanned: (, push into the stack.
• Next symbol scanned: d , append to the Q.
• Next symbol scanned: * , push into the stack because precedence of stack
top operator is lowest.
• Next scan symbol: e , append to Q.
Example: infix to postfix conversion
*
(
+
Opstack
PostString Q: a b c * + d e *
22
23.
• Next Scansymbol: +, pop * from stack and
append it to Q. Then , push + to the stack.
• Next Scan symbol: f , add to Q.
• scan symbol: ), pop + from stack and add to Q.
Pop ( from stack and ignore it.
Example: infix to postfix conversion
+
(
+
Opstack
PostString Q: a b c * + d e * f +
+
Opstack
23
24.
• Input string:a + b * c + ( d * e + f ) * g
• Scan symbol: * , push it into the stack.
• scan symbol: g, add it to Q.
Example: infix to postfix conversion
PostString Q: a b c * + d e * f +
*
+
Opstack
PostString Q: a b c * + d e * f + g
24
25.
• Input stringis no more left to scan, so pop Optack and append
to Q until empty.
• This is the output string in postfix notation.
Example: infix to postfix conversion
PostString Q: a b c * + d e * f + g * +
Opstack
25
26.
Example: infix topostfix conversion
• The following tracing of the algorithm illustrates the algorithm. Consider an
infix expression : ((A-(B+C))*D)$(E+F)
26
27.
Exercise
• Convert thefollowing infix expression to postfix
expression
i. (A+B)*(C+D)/E-F
ii. (A*B)+(C-D)
iii. A$B*C-D+E/F/(G+H)
iv. A-B/(C*D$E)
27
Postfix Evaluation
Algorithm:
Let Pbe an expression written in postfix expression, Vstack be an operand stack.
1. Vstack = empty stack
2. Repeat steps 3, 4 and 5 until end of string, P.
3. Scan one char at a time from left to right in P.
4. If scan char is operand, then read its corresponding value and push it into
vstack.
5. If scan char is operator, then,
a. Pop and place into operand2.
b. Pop and place into operand1.
c. Compute : result = operand1 operator operand2
d. Push result into vstack.
6. Pop vstack and display, which is required value of given expression.
7. End.
29
Infix to PrefixConversion
Algorithm:
Let P be a valid infix expression , Q be prefix stack , Opstack be an operator stack.
1. Make an empty String, Q for prefix stack.
2. Opstack = empty stack
3. Repeat steps 4 to 8, until end of string, P.
4. Scan one char at a time from right to left in P.
5. If scan char is ')', then push it into Opstack.
6. If scan char is operand, then push it to Prefix stack Q.
7. If scan char is operator, then,
a. while(Opstack is not empty and precedence(Opstack_Top)> precedence(scan char))
i. Pop the Opstack and push it to Prefix stack Q.
b. Push the scan operator to Opstack.
8. If scan char is '(', then Pop Opstack and push it prefix stack , until ')' is encountered. Ignore both '(' and ')'.
9. Pop Opstack and Push it to Prefix stack until Opstack is not empty.
10.Pop and print the prefix stack to the prefix string of given infix string.
11.End. 33
34.
Convert infix expressionA-B/C*(C*D$E) to prefix expression.
Scan char Prefix Stack Opstack
) )
E E )
$ E )$
D ED )$
* ED$ )*
C ED$C )*
( ED$C*
* ED$C* *
C ED$C*C *
/ ED$C*C */
B ED$C*CB */
- ED$C*CB/* -
A ED$C*CB/*A -
ɸ ED$C*CB/*A -
34
• The Prefix String of given infix expression is : -A*/BC*C$DE
Example: infix to prefix conversion
Prefix Evaluation
Algorithm:
Let Pbe an expression written in prefix expression, Vstack be an operand stack.
1. Vstack = empty stack
2. Repeat steps 3, 4 and 5 until end of string, P.
3. Scan one char at a time from right to left in P.
4. If scan char is operand, then read its corresponding value and push it into
vstack.
5. If scan char is operator, then,
a. Pop and place into operand1.
b. Pop and place into operand2.
c. Compute : result = operand1 operator operand2
d. Push result into vstack.
6. Pop vstack and display, which is required value of given expression.
7. End.
36
Exercise
• Evaluate thefollowing prefix Expression:
i. +-*+AB/CBA$CB where A =1, B = 2 and C=4
ii. +-*$ ABCD//EF+GH, where A=4, B =2, C=3, D=3, E = 8,
F=4, G =1, H=1
38
39.
Important Questions
1. Definestack as ADT. Write a program for array implementation
of stack.
2. Explain the algorithm for infix to postfix conversion and
evaluation of postfix expression. Trace the algorithms with
suitable example.
3. Explain in-fix to postfix conversion algorithm. Illustrate it with
an example. What changes should be made for converting infix
to prefix?
4. Explain the postfix evaluation algorithm with an example.
39