0% found this document useful (0 votes)
35 views21 pages

Day 3

This document discusses data structures and algorithms, specifically stacks and queues. It provides an overview of stacks and queues, including definitions and examples. It then covers implementations of stacks and queues, as well as applications of each in computing such as parsing expressions, recursion, interrupt handling, and processing block-structured languages for stacks, and task scheduling, buffering, and event handling for queues. Videos are also linked to demonstrate stacks, queues, and their applications.

Uploaded by

Joshua Kofi Addo
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)
35 views21 pages

Day 3

This document discusses data structures and algorithms, specifically stacks and queues. It provides an overview of stacks and queues, including definitions and examples. It then covers implementations of stacks and queues, as well as applications of each in computing such as parsing expressions, recursion, interrupt handling, and processing block-structured languages for stacks, and task scheduling, buffering, and event handling for queues. Videos are also linked to demonstrate stacks, queues, and their applications.

Uploaded by

Joshua Kofi Addo
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/ 21

DATA STRUCTURES & ALGORITHMS

Stack and Queue

By
Samuel K. Opoku
Computer Science Department
Kumasi Technical University

Contents
• Overview of Stacks

• Overview of Queues

• Stack Implementation and Its Applications

• Queue Implementation and Its Applications

1
Videos Links
• Overview of Stacks and Queues
– https://blackboard.skopoku.org/tutorials/stackqueue.mp4

• Stack Implementation and Its Applications


– https://blackboard.skopoku.org/tutorials/stack_app.mp4

• Queue Implementation and Its Applications


– https://blackboard.skopoku.org/tutorials/queue_app.mp4
3

Stacks and its Applications

2
CONTENTS
• Overview of Stack
• Implementation of stack
• Uses of Stacks

Stack
• A stack is a linear list in which insertion and deletion are done one at a
time and only at one end of the list. This is often called Last-In-First-
Out (LIFO)

Examples:

3
Uses of Stack in Computing
1. Use in compilers for parsing arithmetic expressions when converting
them from written form (infix) into reverse polish (suffix) from which is
parenthesis-free

2. Stacks are used frequently in connection with recursive algorithms or


procedures or Subroutine linkage. Recursion is the operation of
defining quantities in terms of themselves.

3. Stacks are very useful in managing complicated sequences of interrupt


or other unpredictable operations. Placing information concerning
program state on a stack where it can later be found is a convenient
way to manage task sequencing in systems programming. Stacks are
so convenient for systems use such that several computers have
automatic stacking of interrupt information

4. Use for processing languages with the nested or block structure. 7

Demonstration of Stack in Programming


Stacks are used to save return addresses in subroutine linkage, procedure
or function calls. Depending on the capacity of the stack, nested
subroutines can be implemented (that is one subroutine calls a second, a
second calls a third and so on)

4
9

STACK IMPLEMENTATION
• A stack is processed by means of a vector X and a stack pointer (that is
a pointer variable T). T points to the top of the stack

• For an empty stack, T = 0. For a stack with only one item, T = 1

• Data can be put onto the stack by incrementing the stack pointer and
transferring the data item onto the stack.

• To move data from the stack, data is transferred from the stack and
the stack pointer decremented.

• One must guard against removing an item from an empty stack


(underflow) or putting an item onto a full stack (overflow)

11

5
INSERTION AND DELETION OF ITEMS
Let a stack with capacity n be represented by the vector X and the pointer T

Insertion Algorithm Deletion Algorithm

TT+1 If T = 0 then
stack underflow, Stop
If T > n then Else
Overflow, Stop data item  X(T)
Else TT–1
X(T)  data item End if
End if

12

APPLICATIONS OF STACK IN ARITHMETIC EXPRESSION


• Conversions of expressions to Polish Notation

• The polish notation is a method of writing arithmetic and logical


expressions without the need for parenthesis. No ambiguity arises in the
evaluation of expressions in Polish form

• In this form, the expression can be evaluated in only one scan: left to right
for Reverse Polish form and right to left for polish form

• The basic structures in different forms are:


1. Infix: operand operator operand eg. a + b
2. Polish form (prefix): operator operand operand eg. + ab
3. Reverse Polish (suffix): operand operand operator eg. ab+

•NB: For unary (acts on only one operand say, ~b or b~) 13

6
EXAMPLES
Convert the following infix expressions to prefix and suffix
1. C + D
Solution: prefix: +CD suffix: CD+
2. X * Y * Z
Solution: prefix: **XYZ suffix: XY*Z*
3. (A + B)/C
Solution: prefix: /+ABC suffix: AB+C/
4. A/B
Solution: prefix: /AB suffix: AB/
5. B = (D + B * C)/A
Solution: prefix: =B/+D*BCA suffix: BDBC*+A/=

Try: Y = (~A+B)*C+D/2 and (Z/R + (W-T)*M)/Q


For efficient code generation (converting to machine language), arithmetic
statements in infix form are converted to reverse polish form (suffix forms).
14

MORE EXAMPLES
1. Convert the following to suffix and prefix forms
i. X = Y * (Z – Y/Z)
ii. (f – (x - a) / f )^ s
iii. K+ (R-T)/5
iv. D = (T-R)/(K-R) + M

2. Convert the following suffix strings to algebraic form:


i. XY+Z/
ii. XFXY*+K/=
iii. xcd^e/ab*+=
iv. a~cd*+bc-/zk~^+

3. Evaluate the following expression


i. 81 6 3 + /
ii. 7 6 2 * 4 / - 15

7
Algorithm – for converting infix to suffix (1/2)
1.Get next character from input string

2. If input character is alphabetic Then


2.1 Transfer input character to output string
2.2 Go to 1
End If

3. If input character is ‘(‘ Then


3.1 Push onto stack
3.2 Go to 1
End if

4. If input character is ‘)’ Then


4.1 Pop items from stack until ‘(‘ is encountered
4.2 Transfer popped items to output string
4.3 Pop ‘(‘ from stack and discard it together with ‘)’
4.4 Go to 1
End if 16

Algorithm – for converting infix to suffix (2/2)


5. If input character is operator with priority > top of stack operator’s priority OR top of
stack is ‘(‘ OR stack is empty Then
5.1 Push input character onto stack
5.2 Go to 9
End If

6. Pop the top of the stack

7. Transfer popped item to output string

8. Go to 5

9. If top stack is ‘;’ Then


9.1 Display output string which is the required suffix string
9.2 Stop
Else
9.3 Go to 1
End if
17

8
Queues and its Applications

18

CONTENTS
• Overview of Queues
• Types of Queues
• Applications of Queues in computing

19

9
OVERVIEW OF QUEUES (1/3)
• A queue is a linear list in which the items are deleted in the same
order in which they are inserted.

• A collection whose elements are added at one end (the rear or tail of
the queue) and removed from the other end (the front or head of the
queue)

• A queue is a FIFO (first in, first out) data structure

• Any waiting line is a queue:


– The check-out line at a grocery store
– The cars at a stop light
– An assembly line

20

CONCEPTUAL VIEW OF A QUEUE


Adding an element

Front of queue

New element is
added to the rear of
the queue

6-21

10
CONCEPTUAL VIEW OF A QUEUE
Removing an element

New front element of queue

Element is removed
from the front of the
queue
6-22

USES OF QUEUES IN COMPUTING


• Queues are useful in managing tasks/jobs waiting to be executed
or are currently executed when it is desirable to service requests on
a FIFO basis. Example: Printer queue (e.g. printer in MC 235), GUI
event queue (click on buttons, menu items)

• Implication/output buffers: To speed input/output, records are


read or written in advance and arranged in input/output buffers on a
FIFO basis before they are sent to memory for processing or written
out to the external device. Example: Keyboard input buffer

• In simulation studies, where the goal is to reduce waiting times:


– Optimize the flow of traffic at a traffic light
– Determine number of cashiers to have on duty at a grocery store at
different times of day
23

11
QUEUE OPERATIONS
• Enqueue : add an element to the tail of a queue

• Dequeue : remove an element from the head of a queue

• First : examine the element at the head of the queue (“peek”)

• Other useful operations (e.g. is the queue empty)

• It is not legal to access the elements in the middle of the


queue! 6-24

OPERATIONS ON A QUEUE
Operation Description

dequeue Removes an element from the front of the queue

enqueue Adds an element to the rear of the queue

first Examines the element at the front of the queue

isEmpty Determines whether the queue is empty

size Determines the number of elements in the queue

toString Returns a string representation of the queue

6-25

12
6-26

IMPLEMENTATION OF QUEUES
• A vector and TWO pointers F (Front pointer – Pointing one location
ahead of the next element to be removed or service) and R (Rear
pointer – Pointing to the last item that was inserted)
• Empty Queue: F = R = 0
INSERTION ALGORITHM

RR+1
• 1st Item:
If R > N Then

Overflow, Stop

Else
• Overflowed (Full Queue)
X(R)  data item

End If

27

13
IMPLEMENTATION OF QUEUES
• Neither overflow nor underflow occurs in the following:

DELETION ALGORITHM

If F = R Then

Underflow, Stop
• Underflow (empty queue)
Else

FF+1

data item  X(F)

End If

28

CIRCULAR QUEUES (1/3)


• As items are added and removed F follows R. This implementation leads
to wastage of storage

• This inefficient use of storage may be overcome by moving the whole


queue to the beginning of the vector each time a deletion takes. The
execution time would be poor

• Circular queue is used to overcome this problem. If X(1), X(2) ... X(N)
are the nodes of the vector then X(1) is made to follow X(N). Thus when
the end of the queue is reached, it is made to move to the beginning if
there is room 29

14
Conceptual Example of a Circular Queue
front
After 5
1 After 7 enqueues 1 dequeues
0 0

front
12 12
11 11
rear rear
10 10

rear
1
0

front
12
11
After 8 more enqueues
10
6-30

CIRCULAR QUEUES (2/3)


• Illustrations:

• In the above representation, if F = R 0, then it is impossible to


distinguish between an empty queue and a full queue and a subsequent
queue operation causes a program crash

31

15
CIRCULAR QUEUES
• This is resolved by never filling the queue completely during insertion.
One space is left unfilled and the queue is said to be full. In such as
situation, the initial setting of the is F = R = 1 but not F = R = 0.

INSERTION ALGORITHM DELETION ALGORITHM

If R = N Then If F = R Then
R1 Underflow, Stop
Else End If
RR+1
End if If F = N Then
F1
If R = F Then Else
Overflow, Stop FF+1
Else data item  X(F)
X(R)  data item End If
End If

32

DEQUE (DOUBLE ENDED QUEUES)


• It is a queue in which items can be added or removed from either end. It
therefore performs both functions of a stack and a queue.
• The representation is the same as circular queue. Algorithms described
for insertion and deletion for the circular queue remain the same
• In addition, algorithms for insertion at the “FRONT” and deletion at the
“REAR” are provided as
INSERTION AT THE FRONT DELETION FROM THE REAR

If F = N Then If R = F Then
F1 Underflow, Stop
Else Else
X(F)  data item data item  X(R)
End if End If

If F = R Then If R = 1 Then
Overflow, Stop RN
Else Else
FF+1 RR-1
End If End If 33

16
USING QUEUES: CODED MESSAGES
• A Caesar cipher is a substitution code that encodes a message by
shifting each letter in a message by a constant amount k
– If k is 5, a becomes f, b becomes g, etc.
• Example: n qtaj ofaf
– Used by Julius Caesar to encode military messages for his
generals (around 50 BC)
– This code is fairly easy to break!

• Modern version: Rotate 13 (ROT13)


– Each letter is shifted by 13
– Used in online forums as a means of hiding spoilers, puzzle
solutions, and offensive materials from the casual glance”

34

USING QUEUES: CODED MESSAGES


• An improvement: change how much a letter is shifted depending on where the
letter is in the message

• A repeating key is a sequence of integers that determine how much each


character is shifted. Example: consider the repeating key: 3 1 7 4 2 5
– The first character in the message is shifted by 3, the next by 1, the next by 7,
and so on. When the key is exhausted, start over at the beginning of the key
– We can use a queue to store the values of the key dequeue a key value when
needed. After using it, enqueue it back onto the end of the queue

Encoded message

n o v a n j g h l m u u r x l v
Key 3 1 7 4 2 5 3 1 7 4 2 5 3 1 7 4
k n o w l e d g e i s p o w e r
Decoded message 6-35

17
More Questions
1. Encrypt “Data Structures and Algorithms” using
i. Caesar cipher with a key of 7
ii. ROT 13
iii. Using the keys 9, 5, 7, 3

2. Decrypt
i. “SBQ” using Caesar cipher with a key of 8
ii. “evpr” using ROT 13
iii. “M mrof clfv” using the keys 4, 1, 9

36

37

18
Assignment

Deadline: Sunday 11th June 2023,


11:59pm

38

Question A
1.Convert the following expressions into polish and reverse
polish form:
i. Z = (Q - D) * (A + B) / T
ii. W = (~X) / Y * T + Q
iii. P = A+ D * (B - C) / T
iv. W = (X + Y) / (~ T) + Q

2. Convert the following from suffix form into infix form:


i. 81 15 3 + /
ii. 5 8 2 * 4 / *
iii. 4 9 2 3 + * /
iv. 4 7 1 + 8 / * 39

19
Question B
1. Encrypt “Kumasi Technical University” using
i. Caesar cipher with a key of 3
ii. ROT 13
iii. Using the keys 6, 5, 7, 9

2. Decrypt
i. “dvd” using Caesar cipher with a key of 7
ii. “ynaqybeq” using ROT 13
iii. “M mxzf hen” using the keys 4, 1, 9

40

Question C
1. A Stack S of size n, stack pointer T which points to first free space
in the stack. Give
(i) underflow and overflow conditions
(ii) write an algorithm to push the data item X onto the stack

2. A string of characters is delimited by “;”. Using a stack, reverse the


string. Give the algorithm

41

20
HIT ANY KEY TO END DAY 3

42

21

You might also like