03 Stacks Queues 6 Labs

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 56

Stacks and Queues

Stacks & Queues 1


Introduction

When a problem is having been solved, some data are


created and they must be processed in a specific order such
as:
LIFO: Last In First Out  Figure of a stack
FIFO: First In First Out  Figure of a queue.
Stacks and Queues are lists in which the way of adding or
removing an element must follow pre-defined rules (LIFO
or FIFO). So, they are restricted lists.
In this topic, ways to create stacks and queues in a program
are introduced.

Stacks & Queues 2


Introduction…
How to Find a Treasure (Money) or To Exit a Maze

The problem can be solve by trial and error approach(THỬ VÀ SAI-mò) using a Stack.

At each crossroad, a If the blue path is


position is chosen chosen, positions must
and OTHERS must be saved are:
be saved.
Example:
From the Entry
(3,0), going to the
position (3,1). There
are two options, the (4,7)
position (2,1) is (2,3)
chosen and the (4,1)
position (4,1) is At the dead position, (9,9),
saved. the next examined position
is chosen is (4,7)
3 Stacks & Queues
Learning Outcomes

LO2.1 Define stack and queue.


LO2.2 List and demonstrate the operations common to
stacks and queues.
LO2.3 Describe specific tasks to which stacks and queues are
suited.
LO2.4 Apply stacks to a specific application.
LO2.5 Apply queues to a specific application.
LO2.6 Write programs to implement stack and queue in Java
programming language.
LO2.7 Define and explain the need of priority queue.

4 Stacks & Queues


Contents

1- Stacks
2- Queues
3- Priority Queues
Exercises: 6 assignments in demonstrations.

Stacks & Queues 5


1- Stacks

A stack is a linear data structure that can be accessed only


at one of its ends for storing and retrieving data.
A stack is called an LIFO structure: last in/first out

A series of operations executed on a stack

Stacks & Queues 6


Stacks…

Where a stack should be used?


Stack should be used when processing order of data is
opposed to creating order.

n= 12 : 2
base=2
0 6:2
Convert a positive 0 3:2
1100
number to a binary 1 1:2
string. 1

1
1
0
0

Stacks & Queues 7


Stacks: How to Implement a stack?

Step 1: Choose a linear storage (an array or a linked list).


Step 2: Implements basic methods which will make a list
as a stacks such as:
clear() — Clear the stack
isEmpty() — Check to see if the stack is empty
push(el) — Put the element el on the top of the stack
pop() — Take the topmost element from the stack
topEl() — Return the topmost element in the stack
without removing it
The LIFO mechanism is implemented in methods
push(…) and pop(…).

Stacks & Queues 8


Stacks: How to Implement a Stack?

Comparing Array Stack vs Linked-list Stack

Stack Using array  linear Using linked list  Evaluating


group linear group
Memory Stack size must be Memory of an element LL stack is more
allocation predicted will be allocated when flexible than array
needed stack.
Basic Add to the end Add to the end With respect to
methods:  push(x)  O(1)  O(1) performance, they
push(x) Remove from end  Remove from end are the same
pop() pop() O(1)  O(1)
OR
Add to the head  O(1)
Remove from the head
 O(1)

Stacks & Queues 9


Stacks: Demo 1
Problem: Convert a positive integer to b-based num string

The java.util.Stack
uses an array in it’s
implementation.

Stacks & Queues 10


Stacks: …
Matching delimiters- A way to use stacks
a = b + (c – d ) * (e – f);
g[10] = h[i[9]] + (j + k) * l; Matched
while (m < (n[8] + o)) { p = 7; r = 6; }

a = b + (c – d) * (e – f));
g[10] = h[i[9]] + j + k) * l; Mismatched
while (m < (n[8] + o]) { p = 7; r = 6; }

while (m < (n[8] + o)) Nested matched

Algorithm for delimiter matching : refer to the page 142.

Stacks & Queues 11


Stacks…

Push to the
stack an open
delimiter and
pop it from
the stack
when
appropriate
close
delemiter is
detected in
input string

Processing the statement s=t[5]+u/(v*(w+y));


with the algorithm delimiterMatching()
Stacks & Queues 12
Stacks…

Figure 4-2 Processing the statement s=t[5]+u/(v*(w+y));


with the algorithm delimiterMatching()
Stacks & Queues 13
Stacks: Demo 2
Adding two 10-based string numbers

Carry=0 Carry=0 Carry=1 Carry=1

Pop all elements


in the result-stack
to make the final
result

An example of adding string numbers “592” and “3784” using stacks


Stacks & Queues 14
Stacks: Demo 2
Adding 2 digit with specific carry and result digit is put to result stack.
New carry is the return value.

Stacks & Queues 15


Stacks: Demo 2
Adding 2 string numbers. Result string number is returned.

Stacks & Queues 16


Stacks: Demo 2

Test program: “592” + “3784”  “4376”

Stacks & Queues 17


Stacks…
Stacks in Java library: The java.util.Stack class.

Stack is a subclass of the Vector class.


So, it is a dynamic array stack.

Stacks & Queues 18


Stacks…
Stacks in Java library: Using the
java.util.LinkedList class as a stack:

To use the java.util.LinkedList object as a stack, ONLY ONE SIDE


is used.
Operation The left side is used The right side is used
Add x to stack addFirst(x) add(x), addLast(x)
Remove from stack remove(), removeFirst() removeLast()

Stacks & Queues 19


Stack: Demo 3.

Evaluating a simple postfix expression using stack.

StringTokenizer:
3
4
*
5
6
*
+
3
/

Stacks & Queues 20


Stack: Demo 3…

Stacks & Queues 21


Stack: Demo 3...

Stacks & Queues 22


Stack: Demo 3.

Evaluating a simple postfix expression.

Demo 4: (Do yourself) Implement a program that will


evaluate a prefix expression(Class PrefixEvaluator)

Stacks & Queues 23


Stack: Demo 5, The Maze Problem

Result:
11111111111
10000010001
10101010101
E0101000101
10111110101
10101000101
10001010101
11111010101
101M1010101
10000010101
11111111111
Result path :
[(3,0, E), (3,1, 0), (2,1, 0), (1,1, 0), (1,2, 0), (1,3, 0), (1,4, 0), (1,5, 0), (2,5, 0), (3,5, 0), (3,6,
0), (3,7, 0), (4,7, 0), (5,7, 0), (5,6, 0), (5,5, 0), (6,5, 0), (7,5, 0), (8,5, 0), (9,5, 0), (9,4, 0),
(9,3, 0), (8,3, M)]
BUILD SUCCESSFUL (total time: 0 seconds)

Stacks & Queues 24


Stack: Demo 5: The Maze Problem…

Stacks & Queues 25


Stack:
Demo 5:
The Maze
Problem…

Stacks & Queues 26


Stack: Demo 5: The Maze Problem…

Một cell hợp lệ khi tọa


độ của nó nằm trong
bàn cờ và có thể đến
được

Stacks & Queues 27


Stack: Demo 5: The Maze Problem…

row-1,
col

row, row, row,


col-1 col col+ 1

row+1,
col

Stacks & Queues 28


Stack: Demo 5: The Maze Problem…

Stacks & Queues 29


Stack: Demo 5: The Maze Problem…

11111111111
10000010001
10101010101
E0101000101
10111110101
10101000101
10001010101
11111010101
101M1010101
10000010101
11111111111
Stacks & Queues 30
Stack: Demo 5: The Maze Problem…

11111111111
10000010001
10101010101
E0101000101
10111110101
10101000101
10001010101
11111010101
101M1010101
10000010101
11111111111

Stacks & Queues 31


Stack: Demo 5: The Maze Problem…

Stacks & Queues 32


2- Queues

A queue is a waiting line that grows by adding elements to its end and
shrinks by taking elements from its front
A queue is a structure in which both ends are used:
One for adding new elements
One for removing them
A queue is an FIFO structure: first in/first out
Where a queue should be used?
A queue should be used when processing order of data is the same as
creating order.
Examples:
 Queue for customers who are waiting for paying money in a shopping
store.
 Printing server: A program receives all printing requirements in a
network environment.
Stacks & Queues 33
Queues: How to Implement a queue?

Step 1: Choose a linear storage (an array or a linked list).


Step 2: Implements basic methods which will make a list as
a queue such as:
clear() — Clear the queue
isEmpty() — Check to see if the queue is empty
enqueue(el) — Put the element el at the end of the
queue
dequeue() — Take the first element from the queue
firstEl() — Return the first element in the queue without
removing it.

Stacks & Queues 34


Queues …

A series of operations executed on a queue

Array queue vs Linked list queue

List Using array  linear group Using linked list  linear


group
Queue Add to end  enqueue(x) O(1) Add to the end  O(1)
enqueue(x) Remove from beginning  dequeue() Remove from beginning 
dequeue()  Shift up  O(n)  Improvement: O(1)
circular array  O(1)

Stacks & Queues 35


Queues using circular array
If an array is used to
store elements of a
remove Add
queue the 2 indexes
must be used to mark Circular array
the beginning and the
last positions.
remove Add

If we do not want to
shift elements when
an element is pick out
the queue then a
circular mechanism Add remove
is used.
 What configuration
will describe the queue
is full?

Figure 4-9 Two possible configurations in an array implementation


of a queue when the queue is full

Stacks & Queues 36


Queues using circular array…
Read by yourself

Figure 4-10 Array implementation of a queue

Stacks & Queues 37


Queues using circular array…

Read by yourself

The queue is full or empty


 Add to the position 0,
circular adding

Figure 4-10: Array implementation of a queue (continued)

Stacks & Queues 38


Queues using circular array…
Read by yourself

In case of only one element

In case of first in the end of array


 circular increaseing
Normal case

Figure 4-10 Array implementation of a queue (continued)

Stacks & Queues 39


Queues using Linked lists

Remember
-One side for adding an element to the queue(enqueue)
- Other side for removing an element (dequeue)

Operation Methods are used


Enqueue an element add(x), addLast(x)
Dequeue an element remove(), removeFirst()

Stacks & Queues 40


Queues: Demo 6

This demonstration will depict activities in a shopping store.


Customers buy products, an accountant will print an invoice
for each customer waiting in a queue.

Activities of customers and accountant’s activity are


proceeded concurrently  Multi-thread programming is
used.

In this demonstration, multi-threading programming in Java


is introduced.

Stacks & Queues 41


Queues: Demo 6…
Introduction to multi-threading:
 CPU has some processors and it is multi-core. A core is a
processor.
 A core may contain some instruction pipelines. Each pipeline can
run a method independently. So, in a process (program in
running), some methods can really performed concurrently
 A thread is a specific code unit (a method run()) in running. Each
language supports it’s own way to make an object being a thread.
 A process can have some threads. As default, a process has ONE
thread of the main(…) method.
 Threads in a process are managed by a scheduler implemented in
operating system or run-time environment (Java Virtual
Machine, java.exe)

Stacks & Queues 42


Queues: Demo 6…

Multi-threading in Java:
Java supports multi-threading. The java.lang.Runnable
interface declares a method of a Java thread, public void
run(void).
The topmost class of Java thread is the java.lang.Thread.
This class implemented the Runnable interface.
2 ways to create threads in Java
 (1) Create a class implementing the Runnable interface
 (2) Create a sub-class of the Thread class should be defined in
which the run() method should be overridden appropriately.
The following demonstration depicts both of two ways above.

Stacks & Queues 43


Queues: Demo 6…
Multi-threading in Java:
 Each thread has a name and common use methods of threads are:
 start() : register the thread with the scheduler then it’s run()
method is called aqutomaticaaly when it is chosen by the
scheduler.
 stop(): un-register the thread from the scheduler. This method
is not safe in case of there is common resource between threads.
 yield(): inform to the scheduler that it want to stop using CPU
 Yielding CPU to other threads  A way to stop a thread
safely.
 sleep(milliSec) : Pause the thread a duration
 isAlive(): checking existence of a thread .
 For more details:
https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/lan
g/package-summary.html

Stacks & Queues 44


Queue: Demo 6

- Thread for accountant’s activity will be implemented using


the Runnable interface.
- Class for a customer will be sub-class of the Thread class.

Stacks & Queues 45


Queue Demo 6…

Stacks & Queues 46


Queue Demo 6…

Stacks & Queues 47


Queue Demo 6…

Stacks & Queues 48


Queue Demo 6…

Stacks & Queues 49


3- Priority Queues
 Priority: External factor is applied on each data object. It is
commonly an integer.

In priority queue, each element is assigned it’s own priority.

In de-queue operation, the element having the highest


priority must be chosen.

When an data object is en-queued, it will be put to a suitable


position  After a new element is added to the end of the
queue, some updates may be performed to ensure that the
highest priority element is put at the beginning of the queue.

Stacks & Queues 50


A Priority Queue using Array
Init empty queue Evaluation:
Enqueue 5 5 (Based-on shift
operations)
Enqueue 3 5 3
-En-queue:
Enqueue 7 7 5 3
The best case,
Enqueue 1 7 5 3 1 highest priority 
Adding to the end
Dequeue 1 7 5 3
 O(1)
Enqueue 0 7 5 3 0 The worst case,
lowest priority 
Enqueue 10 10 7 5 3 0 Adding to the
beginning 
Dequeue  0 10 7 5 3
O(n)
Enqueue 6 10 7 6 5 3
- De-queue:
Dequeue  3 10 7 6 5 Removing from
the end  O(1)

Stacks & Queues 51


Priority Queues (continued)

 Where priority queues are used?


 Schedulers in operating systems  Priority schedulers
 Schedulers in automatic processing applications.

 Priority queue implementations:


(1) Using a totally ordered list (array or linked list)  Cost
of en-queue operations.
(2) A heap, it will be introduced in the chapter Trees.

Stacks & Queues 52


Learning Outcomes
 LO2.1 Define stack and queue.
 LO2.2 List and demonstrate the operations common
to stacks and queues.
 LO2.3 Describe specific tasks to which stacks and
queues are suited.
 LO2.4 Apply stacks to a specific application.
 LO2.5 Apply queues to a specific application.
 LO2.6 Write programs to implement stack and
 queue in Java programming language.
LO2.7 Define and explain the need of priority
queue.

Stacks & Queues 53


Summary

A stack is a linear data structure that can be accessed at


only one of its ends for storing and retrieving data.
A stack is called an LIFO structure: last in/first out.
A queue is a waiting line that grows by adding elements to
its end and shrinks by taking elements from its front.
A queue is an FIFO structure: first in/first out.

Stacks & Queues 54


Ôn tập – Viết vào vở
1- Danh sách hạn chế là gì?
2- Stack được gọi là danh sách hạn chế vì lý do gì?
3- Hai tác vụ cơ bản nhất trên stack là gì?
4- Nếu DSLK được dùng để hiện thực stack, hai tác vụ cơ bản trên stack có
độ phức tạp thời gian là bao nhiêu?
5- Khi nào stack được khuyên dùng?
6- Queue được gọi là danh sách hạn chế vì lý do gì?
7- Hai tác vụ cơ bản nhất trên queue là gì?
8- Nếu DSLK được dùng để hiện thực queue, hai tác vụ cơ bản trên queue có
độ phức tạp thời gian là bao nhiêu?
9- Khi nào queue được khuyên dùng?
10- Với bài toán đổi số hệ 10 sang hệ 2, stack hay queue được khuyên dùng?
11- Sử dụng lớp java.util.LinkedList như là một queue có được không? Tại
sao?
12- Hàng đợi ưu tiên được hiện thực bằng gì?

Stacks & Queues 55


Ôn tập – Viết vào vở

13- Suppose that a stack of integers, named stk, is empty.


Examine the following code:
stk.push(1); stk.push(3); stk.push(5); stk.push(7);
stk.push(9); stk.push(10); stk.push(11); stk.push(13);
while (!stk.empty()) {
stk.pop();
System.out.print(stk.pop() + “,”);
}
What we can see in the output?

Stacks & Queues 56

You might also like