Chapter 5 Stack and Queue - Teacher
Chapter 5 Stack and Queue - Teacher
Stacks And
Queues
1
Part one
2
Quick Introduction
3
Basic Stack Operations
4
Abstract data type: Stack
There are many times where it is useful to use a list
in a way where we always add to the end, and also
always remove from the end.
The last element put into the list will be the first
element we take out of the list.
Last-In, First-Out ("LIFO")
stack: a more restricted List with the following
constraints:
Elements are stored by order of insertion from
"bottom" to "top“.
Items are added to the top.
Only the last element added onto the stack (the
top element) can be accessed or removed.
Goal: every operation on a stack should be O(1).
Stacks are straightforward to implement in several
different ways, and are very useful.
Operations on a stack
push: add an element to the top.
pop: remove and return the element at5 5
the top.
Stack … (continued)
push(a)
push(b)
pop()
6
6
Stack … (continued)
Stack features:
ORDERING: maintains order elements were added
(new elements are added to the end by default).
OPERATIONS:
Add element to end of stack ('push')
Remove element from end of stack ('pop')
Examine element at end of stack ('peek')
Clear all elements from stack (‘makeEmpty’)
Check whether stack is empty or not (‘isEmpty’)
Find size of stack (‘getSize’)
All of these operations are efficient! O(1).
Stacks in computer science
the lowly stack is one of the most important data structures
in all of computer science
Function/method calls are placed onto a stack.
Compilers use stacks to evaluate expressions.
Stacks are great for reversing things, matching up7 related
pairs of things, and backtracking algorithms. 7
Stack … (continued)
8
8
Additional Notes
Stacks structures are usually implemented using
arrays or linked lists.
9
Stack Applications
Reversing Data:
We can use stacks to reverse data.
(example: files, strings).
Very useful for finding palindromes.
Consider the following pseudo code:
1) read (data)
2) loop (data not EOF and stack not full)
1) push (data)
2) read (data)
3) Loop (while stack notEmpty)
1) pop (data)
10
2) print (data)
Converting Decimal to Binary:
Consider the following pseudo code:
1) Read (number)
2) Loop (number > 0)
1) digit = number modulo 2
2) print (digit)
3) number = number / 2
11
The problem with this code is that it will print the
binary number backwards.
12
Infix to Postfix Conversion
Prefix: + a b
Postfix: a b +
13
In high level languages, infix notation cannot be used to evaluate expressions.
We must analyze the expression to determine the order in which we evaluate it.
A common technique is to convert a infix notation into postfix notation, then evaluating it.
14
Rules:
• Operands immediately go directly to output
• Operators are pushed into the stack
(including parenthesis)
Check to see if stack top operator is less than
current operator
If the top operator is less than, push the current
operator onto stack
If the top operator is greater than (or equal to)
the current, pop top operator and append on
postfix notation, push current operator onto
stack.
If we encounter a right parenthesis, pop from
stack until we get matching left parenthesis. Do
not output parenthesis.
15
Precedence Priority of
operators:
Priority 4: ‘(‘ - only popped if a matching
‘)’ is found.
Priority 3: All unary operators ( sin,
cosin,….)
Priority 2: / *
Priority 1: + -
16
Example 1:
A + B * C - D / E
A + B * C - D / E empty empty
+ B * C - D / E empty A
b) B * C - D / E + A
c) * C - D / E + A B
d) C - D / E + * A B
e) - D / E + * A B C
f) D / E + A B C *
g) / E - A B C *+
h) E - / A B C *+ D
i) - / A B C *+
D E
j) empty A B C *+ D E / -
17
Example 2:
A * B - ( C + D ) + E
A * B - ( C + D ) + E empty empty
a) * B - ( C + D ) + E empty A
c) B - ( C + D ) + E * A
d) - ( C + D ) + E * A B
e) - ( C + D ) + E empty A B *
f) ( C + D ) + E - A B *
g) C + D ) + E - ( A B *
h) + D ) + E - ( A B * C
i) D ) + E - ( + A B * C
j) ) + E - ( + A B * C D
k) + E - A B * C D +
l) + E empty A B * C D + -
m) E + A B * C D + -
n) + A B * C D + - E
18
o) empty A B * C D + - E +
Example 3:
a + b * c + ( d * e + f ) * g
Infix Stack(bottom->top) Postfix
a+b*c+(d*e+f)*g empty empty
a) +b*c+(d*e+f)*g empty a
b) b*c+(d*e+f)*g + a
c) *c+(d*e+f)*g + a b
d) c+(d*e+f)*g + * a b
e) +(d*e+f)*g + * a b c
f) +(d*e+f)*g + a b c *
g) +(d*e+f)*g empty a b c * +
h) (d*e+f)*g + a b c * +
i) d*e+f)*g + ( a b c * +
j) *e+f)*g + ( a b c * + d
k) e+f)*g + ( * a b c * + d
l) +f)*g + ( * a b c * + d e
m) f)*g + ( + a b c * + d e *
n) )*g + ( + a b c * + d e * f
o) *g + a b c * + d e * f +
19
p) g + * a b c * + d e * f +
q) + * a b c * + d e * f + g
Postfix Evaluation
Pseudo code:
Operand: push
Operator: pop 2 operands, do the math, push result
back onto stack
1 2 3 + *
Postfix Stack( bot -> top )
a) 1 2 3 + *
b) 2 3 + * 1
c) 3 + * 1 2
d) + * 1 2 3
e) * 1 5 //5 from
2+3 20
f) 5 // 5 from 1 * 5
Page-visited history in a Web browser
To Undo and Redo in a text editor:
Pseudocode:
Accept the command
if(command==Undo)
push_RS(pop_US( ))
else if(command==Redo)
push_US(pop_RS())
else
pushUS(command)
21
Implementation of Stacks
Stack data structure can be implemented in two ways.
Arrays (static: the size of stack is given initially)
Linked lists (dynamic: never become full)
22
Conti……
Pop() {
if stack not empty {
return the value of the top
item(optional)
remove the top item from the stack
}
else {
give an error message
}
}
createStack() {
remove existing items from the stack
initialize the stack to empty
} 23
Array Implementation of Stacks: Push
The PUSH operation
Addition of an element is known as the PUSH operation. So, if
an array is given to you, which is supposed to act as a STACK,
you know that it has to be a STATIC Stack; meaning, data will
overflow if you cross the upper limit of the array.
Algorithm:
25
Array Implementation of Stacks:
Pop
POP Operation
POP is the synonym for delete when it comes to Stack.
So, if you're taking an array as the stack, remember that
you'll return an error message, "Stack underflow", if an
attempt is made to Pop an item from an empty Stack.
Algorithm
Step-1: Check If the Stack is empty then give the alert
"Stack underflow" and quit; or else go to step-2
Step-2: Hold the value for the element pointed by the
TOP
Put a NULL value instead
Decrement the TOP by 1
26
C++ function segment for POP operation
using array
void pop(){
if(top==-1) {
cout<<"stack is Empty\n";
}
else {
int del_val=stacks[top];
stacks[top]=NULL;
top--;
cout<<del_val<<"popped out\n";
}
}
27
Display stack elements of array
28
C++ function segment for displaying data
elements of stack
Void peek(){
if(top==-1) {
cout<<"stack is empty\n";
}
else {
cout<<"stack elements are:\n";
for(int I = top; i>=0; i--) {
cout<<stacks[i] <<endl;
}
}
}
29
Linked List Implementation of Stacks:
PUSH
It’s very similar to the insertion operation in a
dynamic singly linked list.
The only difference is that here you'll add the
new element only at the end or top of the
list, which means addition can happen only
from the TOP.
Since a dynamic list is used for the stack, the
Stack is also dynamic, means it has no prior
upper limit set.
So, we don't have to check for the Overflow
condition at all.
30
Steps to push data to stack using singly
linked list
Step 1: Create a newNode with given value.
Step 2: Check whether stack
is Empty (top == NULL)
Step 3: If it is Empty, then set newNode →
next = NULL.
Step 4: If it is Not Empty, then set newNode →
next = top.
Step 5: Finally, set top = newNode.
31
C++ code for push
using namespace node *top=NULL,;
std;
void push(){
struct node{
node *newNode;
int data;
newNode=new node;
node*next;
cout<<"enter new node
}; data\n";
cin>>newNode->data;
if(top==NULL)
top->next=NULL;
else{
newNode->next=top;
top=newNode;
}
} 32
Steps to pop data to stack using
singly linked list
We can use the following steps to delete a node from the
stack...
Step 1: Check whether stack is Empty (top == NULL).
Step 2: If it is Empty, then display "Stack is Empty!!!
Deletion is not possible!!!" and terminate the function
Step 3: If it is Not Empty, then define a Node pointer
'temp' and set it to 'top'.
Step 4: Then set 'top = top → next'.
Step 7: Finally, delete 'temp' (delete temp).
33
C++ code for pop
void pop(){
node*temp;
temp=top;
if(top==NULL){
cout<<"stack underflow!!! deletion not possible\n";
}
else{
top=temp->next;
temp->next=NULL;
delete temp;
}
}
34
C++ code for display
void display(){
node *temp;
if(top==NULL){
cout<<"stack empty\n";
}
else{
cout<<"stack Elements are:\n";
temp=top;
while(temp!=NULL){
cout<<temp->data<<endl;
temp=temp->next;
}
}
} 35
Thanks
? 36
Part Two
37
Queue
38
Queue … (continued)
Operations on a queue
Offer or enqueue: add an element to the back.
Remove or dequeue: remove and return the element at
the front.
peek: return (but not remove) front element:
peek on an empty queue returns null.
Other operations: isEmpty, size.
Queue features
ORDERING: maintains order elements were
added (new elements are added to the end by
default). 39
Queue … (continued)
OPERATIONS:
Add element to end of list ('offer'
or 'enqueue').
Remove element from beginning
of list ('remove' or 'dequeue')
examine element at beginning of
list ('peek').
Clear all elements.
is empty, get size.
All of these operations are
efficient! O(1).
40
The Queue Operations
A queue is like a line of people waiting
for a bank teller. The queue has a front
and a rear.
$ $
Front
Rear
The Queue Operations
Newpeople must enter the
queue at the rear. it is usually
called an enqueue operation.
$ $
Front
Rear 42
The Queue Operations
When an item is taken from the
queue, it always comes from the
front. it is usually called a
dequeue operation.
$ $
Front
Rear
Array Implementation of
Queue
44
A queue can be implemented with an
array, as shown here. For example,
this queue contains the integers 4 (at
the front), 8 and 6 (at the rear).
An array of integers
to implement a We don't care what's in
queue of integers this part of the array.
45
1. Simple Array Implementation
of Queue
4 8 6
46
Front Rear
A Dequeue Operation
When an element leaves the
queue, size is decremented, and
first changes, too. 2 size
1 first
2 last
[0] [1] [2] [3] [4] [5] ...
4 8 6
Front Rear
An Enqueue Operation
3 last
8 6 2
48
Front Rear
2. Circular Array Implementation
of Queue
There is special behaviour at the end
of the array. For example, suppose we 3 size
want to add a new element to this
queue, where the last index is [5]:
3 first
5 last
Front Rear
An Enqueue Operation
0 last
[0] [1] [2] [3] [4] [5]
4 2 6 1
50
Rear
Front
Linked List
Implementation
51
A queue can also be implemented
with a linked list with both a head
(start) and a tail (end) pointer.
Enqueue:- is inserting a node at
the end of a linked list.
Dequeue:- is deleting the first
node in a linked list.
52
13 10 15
nul
l
head_ptr
tail_ptr
Types of Queue
54
Deque (pronounced as Deck)
Front Rear
58
Dequeue()- deletes Aster.
Abebe Alemu Belay Kedir Meron Yonas
Male Male Male Male Female Male
59
Now the queue has data having equal
priority and dequeue operation deletes
the front element like in the case of
ordinary queues.
Thus,
in the above example the
implementation of the dequeue
operation need to be modified.
61
Demerging Queues:
Is the process of creating two
or more queues from a single
queue.
Used to give priority for some
groups of data
62
Example: The following two
queues can be created from the
above priority queue.
Aster Meron
Female Female
64
Merging Queues:
Is the process of creating a
priority queue from two or
more queues.
The ordinary dequeue
implementation can be used to
delete data in the newly
created priority queue.
65
Example: The following two queues
(females queue has higher priority
than the males queue) can be
merged to create a priority queue.
EnqueuePriorityQueue(DequeueMalesQueue());
67
Application of Queues
Thanks
? 70