Unit 2 - Stack
Unit 2 - Stack
STACK
Stack Definition:
● Stack is a linear data structure and it is an ordered collection of items.
● All the items of stack are inserted and removed from the same end and that end is known as TOP of the
stack.
● Random access of items are not possible in stack.
● Every time an element is added, it goes on the top of the stack and the only element that can be
removed is the element that is at the top of the stack.
● Stack follow a particular order in which the operations (insertion/deletion of elements) are performed.
The order is LIFO(Last In First Out) or FILO(First In Last Out).which means the item which is inserted
first will be removed out at last.
● For Eg: stack of books, stack of dishes,stack of cookies etc.
● Stack Representation:
Stack Operations:
Mainly the following 2 basic operations are performed in the stack:
1. Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.
2. Pop: Removes an item from the stack. If the stack is empty, then it is said to be an Underflow
condition.
To use a stack efficiently, we need to check the status of stack as well. For the same purpose, the following
functionality is added to stacks −
i. peek() − get the top data element of the stack, without removing it.
ii. isFull() − check if stack is full.
iii. isEmpty() − check if stack is empty.
When items are being inserted, we may get stack overflow. Now, let us see “What is stack overflow?”
Stack overflow :
● When elements are being inserted, there is a possibility of stack being full.
Once the stack is full, it is not possible to insert any element. Trying to insert an element, even when the
stack is full results in overflow of stack.
● For example, consider the stack shown above with STACK_SIZE 4. We can insert at the most four
elements. After inserting 30, 20, 25 and 10 there is no space to insert any item. Then we say that stack is
full. This condition is called overflow of stack.
2. pop():
Deleting an element from the stack is called pop operation. Only one item can be deleted at a time and
item has to be deleted only from top of the stack.
Example : Performing pop operation when stack already contains 30, 20, 25, and 10.
When items are being deleted, we may get stack underflow. Now, let us see “What is stack under- flow?”
stack under- flow:
● When elements are being deleted, there is a possibility of stack being empty. When stack is empty, it is
not possible to delete any item. Trying to delete an element from an empty stack results in stack
underflow.
● For example, in the above figure 6, after deleting 10, 25, 20 and 30 there are no elements in the stack and
stack is empty. Deleting an element from the stack results in stack underflow.
Stack Implementation:
Stack can be implemented in 2 ways:
● Using Array
● Using Linked List
1. Using Array: When stack is implemented using array then TOP contains index number and using that
index number only element is pushed in and popped out from the correct location.
if(top==size-1)
{
cout<<"stack full can not insert element\n";
}
else
{
top++;
cout<<"Enter element to be pushed\n";
cin>>s[top];
cout<<"Element inserted\n";
}
}
//===================================================
void pop()
{
if(top==-1)
{
cout<<"stack empty can not delete\n";
}
else
{
top--;
cout<<"Element removed\n";
}
}
//====================================================
void display()
{
Output:
1. for push()
2.for pop()
3.for display()
4.for exit()
1
Enter element to be pushed
12
Element inserted
1. for push()
2.for pop()
3.for display()
4.for exit()
1
Enter element to be pushed
13
Element inserted
1. for push()
2.for pop()
3.for display()
Sahyog College,Thane Ms. Deepa Mishra
4.for exit()
1
Enter element to be pushed
14
Element inserted
1. for push()
2.for pop()
3.for display()
4.for exit()
3
| 14 |
|____|
| 13 |
|____|
| 12 |
|____|
1. for push()
2.for pop()
3.for display()
4.for exit()
4
2. Using Linked List: When Stack is implemented using linked list then TOP Contains address of head
node and using that address push and pop is possible.
Adding a node to the stack is referred to as push operation. Pushing an element to a stack in linked list
implementation is different from that of an array implementation. In order to push an element onto the stack,
the following steps are involved.
t=top;
top=top->link;
delete t;
cout<<"\n node deleted\n";
}
}
void display()
{
if(top==NULL)
{
cout<<"\n stack empty \n";
Sahyog College,Thane Ms. Deepa Mishra
}
else
{ node *r;
r=top;
while(r!=NULL)
{
cout<<r->data<<"->";
r=r->link;
}
cout<<"NULL\n";
}
}
int main()
{
int ch;
while(1)
{
cout<<"\n1.push\n2.pop\n3.display\n4.Exit\n";
cin>>ch;
if(ch==1)
push();
else if(ch==2)
pop();
else if(ch==3)
display();
else
exit(0);
}
}
Applications of stack:
1. Conversion of expressions
2. Evaluation of expressions
3. String reverse(Palindrome)
Notation:
The way to write arithmetic expression is known as a notation. An arithmetic expression can be written in
three different but equivalent notations, i.e., without changing the essence or output of an expression. These
notations are −
Infix Notation
Prefix (Polish) Notation
Postfix (Reverse-Polish) Notation
a) Infix Notation:
● In an expression, if an operator is in between two operands, the expression is called an infix expression.
The infix expression can be parenthesized or un-parenthesized. For example,
● a + b is an un-parenthesized infix expression
● (a + b) is a parenthesized infix expression
c) Prefix Notation:
● In an expression, If an operator comes before the operands, the expression is called a prefix expression.
● + A B its an prefix expression
● - 20 10 it's an prefix expression
( ), [ ] 1 (Highest ) L -> R
^(exponent/power) 2 L -> R
* L -> R
3
/ L -> R
% L -> R
+ L -> R
4
- L -> R
= 5 R-> L
Q.2) (4+2) / 3 * 4 -> ( ) has highest priority ,so ( ) will execute first
Solution:
(4+2) / 3 * 4
= 6/3*4
= 2*4
= 8
Q.3) (10+2) * 4 + 3 + (8 – 4)
Solution:
(10+2) * 4 + 3 + (8 – 4)
= 12 * 4 + 3 + (8 – 4)
= 12 * 4 + 3 + 4
= 48 + 3+ 4
= 55
Q.4) 10 – 2 + 3 * 4 ^ 2
Solution:
10 – 2 + 3 * 4 ^ 2
= 10 – 2 + 3 * (4*4 )
= 10 – 2 + 3 * 16
= 10 – 2 + 48
= 8 + 48
= 56
Note: ^ is an exponent/power operator. 4 ^ 2 means 42. To find the 4^2, you need to multiply 4 twice.
1. Scan the Infix Expression from left to right and repeat Step 2 to 5 for each element of infix expression
until the Stack is empty.
2. If an operand is encountered, add it to the postfix expression.
3. If a left parenthesis is encountered, push it onto Stack.
4. If an operator is encountered ,then:
4.1 Repeatedly pop from Stack and add to postfix expression each operator (on the top of Stack)
which has the same precedence as or higher precedence than incoming operator (scanned
operator).
4.2 Else-Add operator to Stack.
5 If a right parenthesis is encountered ,then:
Rule:
● If scanned operator (incoming operator) precedence is higher than the operator in the stack then push the
incoming operator in the stack.
● If scanned operator (incoming operator) precedence is lower or same than the operator in the stack then
pop the operator of the stack and again compare the incoming operator with stack operator.
3 * 43 3 is an operand so print it
Postfix Expression : 4 3 * 2 + 5 -
Q.2) 10 – 2 + 3 * 4 ^ 2
Solution:
Input/scan Stack Postfix expression Description
10 10 10 is operand so print it
2 - 10 2 2 is operand so print it
3 + 10 2 - 3 3 is operand so print it
4 +* 10 2 – 3 4 4 is operand so print it
Postfix Expression : 10 2 - 3 4 2 ^ * +
( (
( ((
( (((
8 ((( 8
+ ( ((+ 8
1 ( ((+ 81
) (( 81+
- ((- 81+
( ((-( 81+
- ((-(- 81+7
4 ((-(- 81+74
) ((- 8 1 + 7 4- -
) ( 8 1 + 7 4- -
/ (/ 8 1 + 7 4- -
( ( /( 81+74--
11 ( /( 8 1 + 7 4- - 11
- ( /(- 8 1 + 7 4- - 11
9 ( /(- 8 1 + 7 4 - 11 9
) (/ 8 1 + 7 4- - 11 9 -
) Stack is empty 8 1 + 7 4- - 11 9 - /
Postfix Expression : 8 1 + 7 4 - - 11 9 - /
Note:
● If left parenthesis ‘(‘ comes then directly put it in the stack, and if right parenthesis ‘)’ comes then
remove all the operator from stack until you get left parenthesis ‘)’.
● Parenthesis is never mentioned in postfix and prefix expression.
● If stack contains an left parenthesis ‘(‘ then incoming operators will never be compared with ‘(‘,
incoming operator will be directly pushed into stack.
K K
+ + K
L + KL
- - KL+
M - KL+ M
* -* KL+ M
N -* KL+ MN
+ + KL+ MN*-
( +( KL+ MN*-
^ + (^ KL+MN*-O
P + (^ KL+ MN*-OP
) + KL+ MN*-OP^
* +* KL+ MN*-OP^
W +* KL+ MN*-OP^W
/ +/ KL+MN*-OP^W*
U +/ KL+ MN*-OP^W*U
/ +/ KL+ MN*-OP^W*U/
V +/ KL+ MN*-OP^W*U/V
* +* KL+ MN*-OP^W*U/V/
T +* KL+ MN*-OP^W*U/V/T
+ + KL+ MN*-OP^W*U/V/T*+
Q + KL+ MN*-OP^W*U/V/T*+Q
5 5
- - 5
2 - 52
+ + 52-
* +* 52-3
4 +* 52–34
Q Q
+ + Q
T + QT
* +* QT
V +* QT V
/ +/ QTV*
U +/ QTV*U
/ +/ QTV*U/
W +/ QTV*U/W
* +* QTV*U/W/
( +* ( QTV*U/W/
P +* ( QTV*U/W/P
^ +* (^ QTV*U/W/P
O +* (^ QTV*U/W/PO
) +* QTV*U/W/PO^
+ + QTV*U/W/PO^*+
N + QTV*U/W/PO^*+N
* +* QTV*U/W/PO^*+N
M +* QTV*U/W/PO^*+NM
- - QTV*U/W/PO^*+NM*+
+ + QTV*U/W/PO^*+NM*+L-
K + QTV*U/W/PO^*+NM*+L-K
QTV*U/W/PO^*+NM*+L-K+
Q.3) (( A + (B-C) * D) ^ E + F )
Solution:
Reverse the above infix expression:
(F+E^(D*(C-B)+A))
Input/scan Stack Prefix expression
( (
F ( F
+ (+ F
E (+ FE
^ (+^ FE
( (+^( FE
D (+^( FED
* (+^(* FED
( (+^(*( FED
C (+^(*( FEDC
- (+^(*(- FEDC
B (+^(*(- FEDCB
) (+^(* FEDCB-
+ (+^(+ FEDCB-*
A (+^(+ FEDCB-*A
) (+^ FEDCB-*A+
( (
( ((
9 (( 9
- ((- 9
11 ((- 9 11
) ( 9 11 -
/ (/
( (/(
( (/((
4 9 11 - 4
- (/(( - 9 11 – 4
7 (/(( - 9 11 – 4 7
) (/( 9 11 – 4 7 -
- (/( - 9 11 – 4 7 -
( (/( - (
1 9 11 – 4 7 - 1
+ (/( - (+
8 9 11 – 4 7 – 1 8
) (/( - 9 11 – 4 7 – 1 8+
) (/ 9 11 – 4 7 – 1 8+ -
) Stack empty 9 11 – 4 7 – 1 8+ - /
Q.1) 10 2 – 3 4 2 ^ * +
Scanned input Stack Description
10 10
2 10 2
3 (10-2) 3
4 (10-2) 3 4
2 (10-2) 3 4 2
A A
B AB
- (A-B)
D (A-B) D
E (A-B) D E
* (A-B) (D*E)
+ ((A-B)+ (D*E))
AB – DE * + = ((A-B)+ (D*E))
Note:
● Each string will be considered as one operand.
● Element at the top of the stack will be considered as 1st operand and previous one will be 2nd
operand…This is only in case of prefix.
Q.1) / - + 8 1 - 7 4 –11 9
Scanned input Stack Description
9 9
11 9 11
4 (11-9) 4
7 (11-9) 4 7
- (11-9) (7-4)
1 (11-9) (7-4) 1
8 (11-9) (7-4) 1 8
Q.2) – * AB * ED
Solution:
Scanned input Stack Description
D D
E DE
* (E*D)
B (E*D) B
A (E*D) B A
* (E*D) (A * B)
- ((A * B) - (E*D))
Input/scan stack
4 4
3 3
* (4*3)
2 (4*3) 2
+ ((4*3)+2)
- (((4*3)+2)- 5)
( (
5 ( 5
- (-
( (- (
2 (- (+ 52
+ (- (+
( (- (+ (
3 (- (+ ( 523
* (- (+ (*
4 (- (+ (* 5234
) (- (+ 5 2 3 4*
) (- 5 2 3 4* +
) stack empty 5 2 3 4* + -
43*2+5- =-+*4325
43*2+5–
=9
Q.2) 5 6 2 + * 12 4 / -
Solution:
5 5
6 5 6
2 5 6 2
12 40 12
4 40 12 4
5 6 2 + * 12 4 / -
= 37
Note:
● Scanning of prefix expression always happens from right to left
● Top of stack is operand 1 and previous one is operand 2
Q.1) + * 4 3 - 2 5
Solution:
Scanned input stack Description
5 5
2 52
3 -3 3
4 -3 3 4
Q.2) - * 5 + 6 2 / 12 4
Solution:
Scanned input stack Description
4 4
12 4 12
2 3 2
6 3 2 6
5 3 8 5
- * 5 + 6 2 / 12 4
= 37
9 9
11 9 11
- 2
4 24
7 24 7
1 231
8 2318
/ - + 8 1 - 7 4 –11 9
=3
Recursion:
● A function that calls itself is known as a recursive function. And, this technique is known as recursion.
● The recursion continues until some condition is met to prevent it.
● To prevent infinite recursion, if...else statement (or similar approach) can be used where one branch
makes the recursive call, and other doesn't.
Example:
void data()
{
data(); /* function calls itself */
}
int main()
{
data();
}
Properties:
A recursive function can go infinite like a loop. To avoid infinite running of recursive function, there are two
properties that a recursive function must have −
● Base criteria − There must be at least one base criteria or condition, such that, when this condition is met
the function stops calling itself recursively.
● Progressive approach − The recursive calls should progress in such a way that each time a recursive call
is made it comes closer to the base criteria.
Output:
● In the above program we calling display() function inside the body of display() function. This is called
recursion.
● But we have not used any condition in above program so in this the display() function will be called
infinite times. That’s why base condition is necessary in recursion.
● In the above program display() function is called inside display() function but with a base condition i.e.
i<=5. It means as long as the value of i is 5 or less than 5 display() function will be called .
● But as the value of i becomes greater than 5, condition will get false and display() function will no more
get called and the program will also not go in infinite loop.
Output:
Output:
Enter a number: 4
Factorial is 24
In the above 7 step all the disks from peg A will be transferred to C given Condition:
If there is only 1 disk in the rod then move the disk from source to destination.
But if there is more than 1 rod then following steps need to be followed:
a) move n-1 disks from source to auxiliary rod using destination rod
b) move nth i.e. last disk from source to destination
c) move n-1 disks from auxiliary rod to destination using source rod
Output:
Enter the number of disks: 3
The sequence of moves involved in the Tower of Hanoi is
Move disk 1 from peg A to peg C
Move disk 2 from peg A to peg B
Move disk 1 from peg C to peg B
Move disk 3 from peg A to peg C
Move disk 1 from peg B to peg A
Move disk 2 from peg B to peg C
Move disk 1 from peg A to peg C