Title: Stacks and Queues
1Stacks and Queues
- 2014, Fall
- Pusan National University
- Ki-Joune Li
2Stack
- Stack
- A Container
- Last-In First-Out (LIFO)
- Access only to the element at the top
- Push Insert an element at the top
- Pop Remove an element from the top
- Example
- Function Invocation
- Previous frame pointer (registers, local
variables) - Return Address, Parameters
3Operations and Implementation
- Operations
- Maintenance creation of a new stack, deletion
of stack - Push and Pop
- IsEmpty and IsFull
- Data Structures
Class Stack private int top,MaxSize
Type stack// public Stack(int
size) Boolean isFull(), isEmpty()
Type pop() void push(Type element)
4Queue
- Queue
- A Container
- First-In First-Out (FIFO)
- Access only to the elements at the front and rear
- Add Insert an element to the rear
- Delete Remove an element from the front
- Example
- Process Scheduling
rear
front
5Operations and Implementation
- Operations
- Maintenance creation of a new queue, deletion
of queue - Add and Delete
- IsEmpty and IsFull
- Data Structures
Whats the problem ?
Class Queue private
int front,rear,MaxSize Type queue//
public Queue(int size) Boolean
isFull(), isEmpty() Type delete()
void add(Type element)
6Circular Queue
Class CircularQueue private
int front,rear,MaxSize Type queue//
public Queue(int size) Type delete()
void add(Type element)
QueueQueue(int size) MaxSizesize queuenew
TypeMaxSize frontrear1
void Queuedelete(Type v) if(frontrear)
queueEmpty() else front(front1)MaxSize
return queuefront
void Queueadd(Type v) newRear(rear1)MaxSiz
e if(frontnewRear) queueFull() else
rearnewRear queuerearv
7Example
void Queueadd(Type v) newRear(rear1)MaxSiz
e if(frontnewRear) queueFull() else
rearnewRear queuerearv
Typr Queuedelete() if(frontrear)
queueEmpty() else front(front1)MaxSize
return queuefront
front
0
1
2
MaxSize-1
3
rear
newRear
front1 rear1
front1 rear1 newRear2
front1 rear2 newRear3
front1 rearMaxSize-1 newRear0
front1 rear0 newRear1
front1 rear2
front1 rear3
front1 rear0
front2 rear0
frontMaxSize-1 rear0
front0 rear0
front0 rear0
8Application of Stack Mazing Problem
How to find the path ?
9Path Finding Algorithm for Mazing Problem
Algorithm PathFinding(int p,int q,int
mazepq) // (p,q) coorinates of exit cell
pathStack ? initialize Stack
pathStack.push((0,0)) while(pathStack.isEmpty()
NO) (i,j)? pathStack.getTop() // read
but not remove while(there is an unvisited
cell (m,n) from (i,j)) pathStack.push((m,n
)) if(mp and nq) // path found
pathStack.print() // pop and print
return (i,j)?(m,n)
pathStack.pop() print No path End
Algorithm PathFinding
10Application of stack Evaluation of Expressions
How to evaluate this ?
X A / B C D E A C
X A B / C D E A C
11Evaluation of Expression in Postfix Notation
X A B / C D E A C
C
/
A
B
-
D
E
D
T6
12Infix to Postfix
A
/
(
B
-
C
)
D
E
-
-
-
(
(
(
(
/
/
/
/
/
/
-
A
B
C
-
/
D
E