0% found this document useful (0 votes)
10 views

3. [DStructure - Slides] Stack

Uploaded by

alieslam20014
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

3. [DStructure - Slides] Stack

Uploaded by

alieslam20014
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 135

Chapter 3

Stacks

Objectives
Upon completion you will be able to

• Explain the design, use, and operation of a stack


• Static implementation (using arrays)
• Dynamic implementation (using pointers)
• Understand the operation of the stack ADT

1
What is a stack?
n A stack is an abstract data structure (ADT) that contains a
collection of elements.
n It is an ordered group of homogeneous items of elements.
n Elements are added to and removed from the top of the
stack (the most recently added items are at the top of the
stack).
n The last element to be added is the first to be removed
(LIFO: Last In, First Out).
3
n A stack is a data structure in which data is added and
removed at only one end called the top.

n To add (push) an item to the stack, it must be placed on


the top of the stack.

n To remove (pop) an item from the stack, it must be


removed from the top of the stack too.

n Thus, the last element that is pushed into the stack, is


the first element to be popped out of the stack.
i.e., A stack is a Last In First Out (LIFO) data structure
An Example of a Stack

2
top
top 8 8
1
top 1
Push(8)
1
7 7 Push(2) 7
2 2 2

pop()

top 8
top 1
1
top 7 7 pop()
2 pop() 7
2
2
OPERATIONS PERFORMED ON STACK

The stack concept is introduced and two basic stack


operations are discussed.

6
Data Structures: A Pseudocode Approach with C 7
Data Structures: A Pseudocode Approach with C 8
Data Structures: A Pseudocode Approach with C 9
10
STACK IMPLEMENTATION
Stack can be implemented in two ways:
1. Static implementation (using arrays)
2. Dynamic implementation (using pointers)
Ø Static implementation using arrays is a very simple

technique but is not a flexible way


Ø static implementation is not an efficient method when

resource optimization is concerned (i.e., memory


utilization)

11
STACK USING ARRAYS

n Implementation of stack using arrays is a very simple technique.


Algorithm for pushing (or add or insert) a new element at the top of the
stack and popping (or delete) an element from the stack is given below.

n Algorithm for push

12
13
Algorithm for pop

14
15
16
17
18
19
Stack Methods
In C++, the stack class provides various methods to perform
different operations on a stack.

Operation Description
push() adds an element into the stack
pop() removes an element from the stack
top() returns the element at the top of the stack
size() returns the number of elements in the stack
empty() returns true if the stack is empty

20
Add element into the stack
We use the push() method to add an element into a stack. For
example,
#include <iostream>
#include <stack>
using namespace std;
int main() {
// create a stack of strings
stack<string> colors;

// push elements into the stack


colors.push("Red");
colors.push("Orange");

cout << "Stack: ";

// print elements of stack


while(!colors.empty()) {
cout << colors.top() << ", ";
colors.pop();
}
return 0;
} 21
22
Remove Elements From the Stack
We can remove an element from the stack using the pop()
method. For example,
// removes "Blue" as it was inserted last
#include <iostream> colors.pop();
#include <stack>
using namespace std; cout << "Final Stack: ";

// function prototype for display_stack utility // print elements of stack


void display_stack(stack<string> st); display_stack(colors);

int main() { return 0;


}
// create a stack of strings
stack<string> colors; // utility function to display stack elements
void display_stack(stack<string> st) {
// push elements into the stack
colors.push("Red"); while(!st.empty()) {
colors.push("Orange"); cout << st.top() << ", ";
colors.push("Blue"); st.pop();
}
cout << "Initial Stack: ";
// print elements of stack cout << endl; 23
display_stack(colors);
24
Access Elements From the Stack
We access the element at the top of the stack using the top() method.
For example,
#include <iostream>
#include <stack>
using namespace std;
int main() {
// create a stack of strings
stack<string> colors;

// push element into the stack


colors.push("Red");
colors.push("Orange");
colors.push("Blue");

// get top element


string top = colors.top();

cout << "Top Element: " << top;


return 0;
} 25
26
Get the Size of the Stack
We use the size() method to get the number of elements in the stack.
For example, #include <iostream>
#include <stack>
using namespace std;
int main() {
// create a stack of int
stack<int> prime_nums;

// push elements into the stack


prime_nums.push(2);
prime_nums.push(3);
prime_nums.push(5);

// get the size of the stack


int size = prime_nums.size();
cout << "Size of the stack: " << size;
return 0;
}
27
28
29
#include <iostream>
#include <stack> // push element into the stack
using namespace std; nums.push(2.3);
nums.push(9.7);
int main() {
cout << "Is the stack
// create a stack of double empty? ";
stack<double> nums;
// check if the stack is empty
cout << "Is the stack empty? "; if (nums.empty()) {
cout << "Yes";
// check if the stack is empty }
if (nums.empty()) { else {
cout << "Yes" << endl; cout << "No";
} }
else {
cout << "No" << endl; return 0;
} }
cout << "Pushing elements..." << endl;

30
31
#include<iostream>
#include<stack>
using namespace std;
main(){
stack<int> stk;
if(stk.empty()){
cout << "Stack is empty" << endl;
} else {
cout << "Stack is not empty" << endl;
}
//insert elements into stack
stk.push(10);
stk.push(20);
stk.push(30);
stk.push(40);
stk.push(50);
cout << "Size of the stack: " << stk.size() << endl;
//pop and dispay elements Output
while(!stk.empty()){ Stack is empty
int item = stk.top(); // same as peek operation
stk.pop();
Size of the stack: 5
cout << item << " "; 50 40 30 20 10
}
} 32
33
APPLICATIONS OF STACKS
Some direct applications:
• Conversion of tail-recursive algorithms to iterative ones.
• Evaluation of arithmetic expressions by compilers [infix to postfix
conversion, infix to prefix conversion, evaluation of postfix
expressions]

Some indirect applications


• Auxiliary data structure for some algorithms
Example: Converting a decimal number to another base
• Component of other data structures
Example: stack to implement a Tree iterator
RECURSION
• Recursion occurs when a function is called by itself repeatedly;
the function is called recursive function. The general algorithm
model for any recursive function contains the following steps:
1. Prologue: Save the parameters, local variables, and return
address.
2. Body: If the base criterion has been reached, then perform
the final computation and go to step 3; otherwise, perform
the partial computation and go to step 1 (initiate a recursive
call).
3. Epilogue: Restore the most recently saved parameters, local
variables, and return address.
RECURSIVE FUNCTION

• The recursive function is


• a kind of function that calls itself, or
• a function that is part of a cycle in the sequence of function
calls.

f1 f1 f2 … fn

10-4
#include<conio.h>
#include<iostream.h>
void fact(int no, int facto)
{
if (no <= 1)
{
//Final computation and returning and restoring address
cout<<“\nThe Factorial is = ”<<facto;
return;
}
else
{
//Partiial computation of the program
facto=facto*no;
//Function call to itself, that is recursion
fact(--no,facto);
}
}
void main()
{
clrscr();
//Initialization of formal parameters, local variables and etc.
factorial=1;
cout<<“\nEnter the No = ”;
cin>>number;
//Starting point of the function, which calls itself
fact(number,factorial);
getch();

1. write program to calculate the sum of natural


numbers using recursion ?
2. What are the difference between Iteration and
Recursion?
DISADVANTAGES OF RECURSION

• 1. It consumes more storage space because the recursive calls along with
automatic variables are stored on the stack.
• 2. The computer may run out of memory if the recursive calls are not
checked.
• 3. It is not more efficient in terms of speed and execution time.
• 4. According to some computer professionals, recursion does not offer
any concrete advantage over non-recursive procedures/functions.
• 5. If proper precautions are not taken, recursion may result in non-
terminating iterations.
• 6. Recursion is not advocated when the problem can be through iteration.
Recursion may be treated as a software tool to be applied carefully and
selectively.
TOWER OF HANOI

• Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs)


and more than one rings is as depicted
• These rings are of different sizes and stacked upon in an ascending order, i.e. the
smaller one sits over the larger one. There are other variations of the puzzle
where the number of disks increase, but the tower count remains the same.
• Rules
• The mission is to move all the disks to some another tower
without violating the sequence of arrangement. A few rules to
be followed for Tower of Hanoi are −
• Only one disk can be moved among the towers at any given
time.
• Only the "top" disk can be removed.
• No large disk can sit over a small disk.
• Following is an animated representation of solving a Tower of
Hanoi puzzle with three disks.
The Tower of Hanoi

5 Tower

A B C
ILLEGAL
MOVE
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
3 Tower

A B C
D E M O 3 TOW E R
The Tower of
Hanoi
3 Tower

A B C
The Tower of
Hanoi
3 Tower

A B C
The Tower of
Hanoi
3 Tower

A B C
The Tower of
Hanoi
3 Tower

A B C
The Tower of
Hanoi
3 Tower

A B C
The Tower of
Hanoi
3 Tower

A B C
The Tower of
Hanoi
3 Tower

7 Moves

A B C
Tower of Hanoi puzzle with n disks can be solved in minimum
2n−1 steps. This presentation shows that a puzzle with 3 disks has
taken 2n - 1 = 7 steps.

Algorithm
To write an algorithm for Tower of Hanoi, first we need to learn
how to solve this problem with lesser amount of disks, say → 1 or
2. We mark three towers with name, source, destination and aux
(only to help moving the disks). If we have only one disk, then it
can easily be moved from source to destination peg.

If we have 2 disks −

First, we move the smaller (top) disk to aux peg.


Then, we move the larger (bottom) disk to destination peg.
And finally, we move the smaller disk from aux to destination peg.
• so now, we are in a position to design an algorithm for Tower of Hanoi with
more than two disks. We divide the stack of disks in two parts. The largest
disk (nth disk) is in one part and all other (n-1) disks are in the second part.
• Our ultimate aim is to move disk n from source to destination and then put
all other (n1) disks onto it. We can imagine to apply the same in a recursive
way for all given set of disks.
• The steps to follow are −
The Tower of
Hanoi
4 Tower

A B C
4 TOWER SHOW
The Tower of
Hanoi
4 Tower

A B C
The Tower of
Hanoi
4 Tower

A B C
The Tower of
Hanoi
4 Tower

A B C
The Tower of
Hanoi
4 Tower

A B C
The Tower of
Hanoi
4 Tower

A B C
The Tower of
Hanoi
4 Tower

A B C
The Tower of
Hanoi
4 Tower

A B C
The Tower of
Hanoi
4 Tower

A B C
The Tower of
Hanoi
4 Tower

A B C
The Tower of
Hanoi
4 Tower

A B C
The Tower of
Hanoi
4 Tower

A B C
The Tower of
Hanoi
4 Tower

A B C
The Tower of
Hanoi
4 Tower

A B C
The Tower of
Hanoi
4 Tower

A B C
The Tower of
Hanoi
4 Tower
15 Moves

A B C
The Tower of
Hanoi
5 Tower

A B C
5 TOWER SHOW
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower

A B C
The Tower of
Hanoi
5 Tower
31 Moves

A B C
The Tower of Hanoi

}
Discs Moves
1 1
2 3 Un = 2Un-1 + 1
3 7
4 15 This is called a
5 31 recursive function.
6 63
7 127
8 255

Write program to simulate the


64 264? -1 tower of hanoi problem in c++?

n 2n?- 1 RESULTS
TABLE
EXPRESSION

Another application of stack is calculation of postfix


expression. There are basically three types of notation
for an expression (mathematical expression; An
expression is defined as the number of operands or data
items combined with several operators.)
1. Infix notation
2. Prefix notation
3. Postfix notation
• The infix notation is what we come across in our general
mathematics, where the operator is written in-between
the operands. For example : The expression to add two
numbers A and B is written in infix notation as:
A+B
Note that the operator ‘+’ is written in between the
operands A and B.
• The prefix notation is a notation in which the operator(s) is
written before the operands, it is also called polish
notation in the honor of the polish mathematician
+A B
As the operator ‘+’ is written before the operands A and B,
this notation is called prefix (pre means before).
• In the postfix notation the operator(s) are written after the
operands, so it is called the postfix notation (post means after), it
is also known as suffix notation or reverse polish notation.
The above expression if written in postfix expression looks like:
AB+
• The order of operations evaluation is determined by the
precedence rules and parentheses.
• When an evaluation order is desired that is different from that
provided by the precedence, parentheses are used to override
precedence rules.
CONVERTING INFIX TO POSTFIX
EXPRESSION
Infix Notation Postfix (Reverse Polish) Prefix (Polish) Notation
Notation
16 / 2 16 2 / / 16 2

(2 + 14)* 5 2 14 + 5 * * + 2 14 5

2 + 14 * 5 2 14 5 * + + * 2 14 5

(6 – 2) * (5 + 4) 6 2 - 5 4 +* * - 6 2 + 5 4
Algorithm
Suppose P is an arithmetic expression written in infix notation.
the equivalent postfix expression Q.
Infix to postfix conversion

infixVect
(a+b-c)*d–(e+f)

postfixVect
Infix to postfix conversion
stackVect

infixVect
a+b-c)*d–(e+f)

postfixVect

(
Infix to postfix conversion
stackVect

infixVect
+b-c)*d–(e+f)

postfixVect
a

(
Infix to postfix conversion
stackVect

infixVect
b-c)*d–(e+f)

postfixVect
a

+
(
Infix to postfix conversion
stackVect

infixVect
-c)*d–(e+f)

postfixVect
ab

+
(
Infix to postfix conversion
stackVect

infixVect
c)*d–(e+f)

postfixVect
ab+

-
(
Infix to postfix conversion
stackVect

infixVect
)*d–(e+f)

postfixVect
ab+c

-
(
Infix to postfix conversion
stackVect

infixVect
*d–(e+f)

postfixVect
ab+c-
Infix to postfix conversion
stackVect

infixVect
d–(e+f)

postfixVect
ab+c-

*
Infix to postfix conversion
stackVect

infixVect
–(e+f)

postfixVect
ab+c-d

*
Infix to postfix conversion
stackVect

infixVect
(e+f)

postfixVect
ab+c–d*

-
Infix to postfix conversion
stackVect

infixVect
e+f)

postfixVect
ab+c–d*

(
-
Infix to postfix conversion
stackVect

infixVect
+f)

postfixVect
ab+c–d*e

(
-
Infix to postfix conversion
stackVect

infixVect
f)

postfixVect

+ ab+c–d*e

(
-
Infix to postfix conversion
stackVect

infixVect
)

postfixVect

+ ab+c–d*ef

(
-
Infix to postfix conversion
stackVect

infixVect

postfixVect
ab+c–d*ef+

-
Infix to postfix conversion
stackVect

infixVect

postfixVect
ab+c–d*ef+-
Evaluating Postfix Expressions

Figure 7-8
The action of a postfix calculator when evaluating the expression 2 * (3 + 4)
Write algorithm and program to
convert
1- Prefix to Infix Conversion
the Infix Expression is ((b-c)/((p-q)+r))
2- Postfix to Infix conversion
the Infix Expression is (e+f-g)* (h-e)/(s-h+o)
3- Infix to Postfix Conversion
the Postfix Expression is 33*41-/62*+

You might also like