Title: CSCI 210 Data Structures
1Data Structures and Algorithms
Stack
1
2The Stack ADT
- Introduction to the Stack data structure
- Designing a Stack class using dynamic arrays
- Linked Stacks
- Some Applications of Stacks
2
31. Introduction to the Stack Data Structure
- A simple data container consisting of a linear
list of elements - Access is by position (order of insertion)
- All insertions and deletions are done at one end,
called top - Last In First Out (LIFO) structure
- Two basic operations
- push add to top
- pop remove from top
3
41. Introduction to the Stack Data Structure
- A simple data container consisting of a linear
list of elements - Access is by position (order of insertion)
- All insertions and deletions are done at one end,
called top - Last In First Out (LIFO) structure
- Two basic operations
- push add to top
- pop remove from top
4
5Example
5
6Example
push
top
top
top
top
top
top--
pop
6
7Some Stack Applications
- Run-time stack used in function calls
- Page-visited history in a Web browser
- Undo sequence in a text editor
- Removal of recursion
- Conversion of Infix to Postfix notation
- Evaluation of Postfix expressions
- Reversal of sequences
- Checking for balanced symbols
7
8Stack Class Operations
- construct construct an empty stack
- stackIsEmpty ? bool return True if stack is
empty - stackIsFull ? bool return True if stack is full
- push(el) add element (el) at the top
- pop(el) retrieve and remove the top element
- stackTop(el) retrieve top element without
removing it
8
92. Array Based Stack Class Definition
- The stack may be implemented as a dynamic array.
- The capacity (MaxSize) will be input as a
parameter to the constructor (default is 128) - The stack ADT will be implemented as a template
class to allow for different element types.
9
10A Stack Class Definition
// File Stackt.h // Stack template class
definition. // Dynamic array implementation
ifndef STACKT_H define STACKT_H
template ltclass Typegt class Stackt
public Stackt (int nelements 128) //
Constructor Stackt (const Stackt ltTypegt ) //
Copy Constructor Stackt () // Destructor
10
11A Stack Class Definition
// Member Functions void push(Type
) // Push void pop(Type ) // Pop
void stackTop(Type ) const // retrieve top
bool stackIsEmpty() const // Test for Empty
stack bool stackIsFull() const // Test
for Full stack private Type
stack // pointer to dynamic array int top,
MaxSize endif // STACKT_H include
"Stackt.cpp"
11
123. Linked Stacks
- A stack can be implemented as a linked structure.
- Requires more space than array implementations,
but more flexible in size. - Easy to implement because operations are at the
top (in this case the head node)
12
13Node Specification
// The linked structure for a node can be //
specified as a Class in the private part of //
the main stack class. class node // Hidden
from user public Type e // stack
element node next // pointer to next node
// end of class node
declaration typedef node NodePointer NodePo
inter top // pointer to top
13
14Push Operation
Last
First
top
2
3
New
push(v) NodePointer pnew new node
pnew-gte v pnew-gtnext top top pnew
1
pnew
14
15Push Operation
Last
First
top
push(v) NodePointer pnew new node
pnew-gte v pnew-gtnext top top pnew
15
16Pop Operation
1
cursor
top
3
2
pop(v) v top-gte cursor top top
top-gtnext delete cursor
16
17Linked Stack Class
// File StackL.h // Linked List Stack class
definition ifndef STACKL_H define
STACKL_H template ltclass Typegt class
StackL public StackL() //
Constructor StackL() // Destructor
void push(Type ) // Push void pop(Type ) //
Pop
17
18Linked Stack Class
void stackTop(Type ) const // retrieve top
bool stackIsEmpty() const // Test for Empty
stack private // Node Class class node
public Type e // stack
element node next // pointer to next node
// end of class node declaration
18
19Linked Stack Class
typedef node NodePointer NodePointer
top // pointer to top endif //
STACKL_H include "StackL.cpp"
19
204. Some Applications of Stacks
- Conversion from Decimal to Hexadecimal
- Balancing Enclosure Symbols
- Evaluation of Postfix Expressions
- Converting Infix Expressions to Postfix
- Backtracking
20
21(a) Decimal to Hexadecimal Conversion
// Covert from Decimal to Hexadecimal string
DEC-to_HEX(n) Stackt ltchargt s string H
do rem n 16 n n / 16 if (rem lt
10) c char (int('0') rem) else c char
(int('A') rem - 10) s.push(c) while ( n
! 0) while (!s.stackIsEmpty()) s.pop(c) H
H c return H
21
22(b) Balancing Enclosure Symbols
Given a text file containing a sequence of
characters, we want to check for balancing of the
symbols ( ) , , . Algorithm bool
EnclosureBalance (filename) Open file
filename Initialize an empty stack of
characters balanced true for each
character (ch) read until end of file
If (ch is a left symbol) push ch on the stack
22
23Balancing Enclosure Symbols
else if (ch is a right symbol) then if
(stack is empty) balanced false else
pop the stack if (popped
symbol is not the corresponding left
symbol) balanced false At the end of
the file, if (stack is not empty) balanced
false return balanced
23
24(c) Evaluation of Postfix Expressions
- Regular expressions are written in infix
notation, i.e., operator between two operands,
e.g., - (AB) (C- (DE))
- Parentheses are used to force precedence
- Reverse Polish Notation (RPN) or postfix does
without parentheses. e.g. the above expression
is - A B C D E -
- Postfix expressions like A B are evaluated as A
B
24
25Evaluation of Postfix Expressions
- The idea is
- Scan from left to right until an operator
(,-,,/) is encountered. - Apply operator between the previous operands.
- Replace the two previous operands by the result.
- This suggests to use a stack to store operands
- and the results.
25
26Evaluation of Postfix Expressions (Example)
A B C D E -
R1 C D E -
R1 C R2 -
R1 C R2 -
R1 R3
R1 R3 RESULT
26
27Evaluation of Postfix Expressions (Example)
(23) (2- (41)) ? 2 3 2 4 1 -
2 3 2 4 1 -
5 2 4 1 -
5 2 5 -
5 2 5 -
5 -3
5 -3 RESULT -15
27
28Evaluation of Postfix Expressions (Algorithm)
- Initialize a stack (S) of characters
- For each character from left to right
- Get next character
- If operand, push it on S
- If an operator
- Pop two values (error if there are no two values)
- Apply operator
- Push result back onto (S)
- At the end, result is on top of (S) (the only
value, otherwise an error)
28
29(d) Conversion from Infix to Postfix Expressions
Initialize an operator stack, s While not end of
infix expression do the following read next
symbol in case the symbol is an
operand write the operand ( push onto
s ) pop and write all operators until
encountering(, then pop ( or
/ 1-pop and write all and / operators
from the top down to but not including the
top most (,,- or to the bottom of
the stack 2-push the or / or
- 1-pop and write all operators from the top
down to but not including the topmost (
or to the bottom of the stack 2-push the
or - End of exp pop and write all
operators
29
30(e) Backtracking (Maze Problem)
- A Maze can be modeled as nodes (decision points)
and edges (tracks). A Backtracking method can be
used to find the way to the exit starting from an
entrance.
in
A
out
F
G
B
E
C
D
30
31Backtracking (Maze Problem)
- We may choose to move in the order
- South East North West
- A stack is used to record the tracks.
- When we move on a new track, we push it on the
stack. - When we run out of tracks, we backtrack by
popping the last track from the stack. - Later in the course, we will do this using a
recursive algorithm using the system stack. The
algorithm is called Depth First Search
31
32Backtracking (Maze Problem)
- The stack will develop as shown
pop
exit
D
C C E G
B B B B B F F
A A A A A A A A
steps
32