SlideShare a Scribd company logo
Stack and Queue
Software University
http://softuni.bg
SoftUni Team
Technical Trainers
Table of Contents
1. Stack - Last In First Out (LIFO)
• Stack Functionality
• Java Stack Implementation
• Overview of All Operations
2. Queue - First In First Out (FIFO)
• Queue Functionality
• Java Stack Implementation
• Overview of All Operations
3. Priority Queue
sli.do
#java-advanced
Have a Question?
 Describes performance of particular algorithm
 Runtime and memory consumption based on the input size N
 We usually care about the worst-case performance
 We measure the complexity as the Big O notation
 Numerical function depending on the input size O(N)
 We measure time as the number of simple steps
 We measure memory as input data N by it's type size
Algorithmic Complexity
 O(1) – Constant time – time does not depend on N
 O(log(N)) – Logarithmic time – grows with rate as log(N)
 O(N) – Linear time grows at the same rate as N
 O(N^2),O(N^3) – Quadratic, Cubic grows as square or cube of N
 O(2^N) – Exponential grows as N becomes the exponent worst
algorithmic complexity
 For input size of 10 - 1024 steps
 For input size of 100 – 1267650600228229401496703205376
steps
 http://bigocheatsheet.com/
Algorithmic Complexity
 Calculate maximum steps to find sum of even elements in an array
 Assume that a single step is a single CPU instruction:
 assignments, array lookups, comparisons, arithmetic operations
Get Sum Number of Steps
int getSumEven(int[] array) {
int sum = 0;
for (int i = 0; i < array.length; i++)
if (array[i] % 2 == 0) sum += array[i];
return sum;
}
Solution:
T(n) = 9n + 3
Counting maximum steps is
called worst-case analysis
 Worst-case
 An upper bound on the running time
 Average-case
 Average running time
 Best-case
 The lower bound on the running time
(the optimal case)
Time Complexity
 Why don't use Stack and Queue?
 Implementation details which make unsecure usability
 In many cases those structures will decrease the performance
 Why to use ArrayDeque?
 Implementation which makes the structure more secure
 Better performance and usability
 Methods which operate as those structures suggest
Stacks And Queue vs. ArrayDeque
Stack
Last In First Out (LIFO)
 Stacks provide the following functionality:
 Pushing an element at the top of the stack
 Popping element from the top fo the stack
 Getting the topmost element without removing it
Stack Functionality
2
10
5
2
10
5
2
10
5
Push Pop Peek
ArrayDeque<E> – Java Stack Implementation
 Creating a Stack
 Adding elements at the top of the stack
 Removing elements
 Getting the value of the topmost element
stack.push(element);
ArrayDeque<Integer> stack = new ArrayDeque<>();
Integer element = stack.pop();
Integer element = stack.peek();
Stack – Utility Methods
ArrayDeque<Integer> stack = new ArrayDeque<>();
int size = stack.size();
boolean isEmpty = stack.isEmpty();
boolean exists = stack.contains(2);
012
5
3
210515
13
Stack – Overview of All Operations
size():
5
-7
45
132
push()
pop()
peek()
Stack<Integer>
 Write a program which takes 2 types of browser instructions:
 Normal navigation: a URL is set, given by a string
 The string "back" that sets the current URL to the last set URL
Problem: Browser History
https//softuni.bg/
back
https//softuni.bg/trainings/courses
back
https//softuni.bg/trainings/2056
back
https//softuni.bg/trainings/live
https//softuni.bg/trainings/live/details
Home
Input
https//softuni.bg/
no previous URLs
https//softuni.bg/trainings/courses
https//softuni.bg/
https//softuni.bg/trainings/2056
https//softuni.bg/
https//softuni.bg/trainings/live
https//softuni.bg/trainings/live/details
Output
Scanner scanner = new Scanner(System.in);
ArrayDeque<String> browser = new ArrayDeque<>();
String line = scanner.nextLine();
String current = "";
// continue…
Solution: Browser History (1)
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
while(!line.equals("Home")) {
if(line.equals("back")) {
if(!browser.isEmpty()) {current = browser.pop();
} else {
System.out.println("no previous URLs");
line = scanner.nextLine();
continue;}
} else {
if(!current.equals("")) { browser.push(current); }
current = line; }
System.out.println(current);
line = scanner.nextLine(); }
Solution: Browser History (2)
 Implement a simple calculator that can evaluate simple
expressions (only addition and subtraction)
Problem: Simple Calculator
2 + 5 + 10 - 2 - 1
Input
2 - 2 + 5
14
Output
5
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
Solution: Simple Calculator (1)
Scanner scanner = new Scanner(System.in);
String[] tokens = scanner.nextLine().split("s+");
Deque<String> stack = new ArrayDeque<>();
Collections.addAll(stack, tokens);
// continues…
Split by regex
Adds a collection to
another collection
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
Solution: Simple Calculator (2)
while (stack.size() > 1) {
int first = Integer.valueOf(stack.pop());
String op = stack.pop();
int second = Integer.valueOf(stack.pop());
switch (op)
case "+": stack.push(String.valueOf(first + second));
break;
case "-": stack.push(String.valueOf(first - second));
break;
}
System.out.println(stack.pop());
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
 Create a converter which takes a decimal number and
converts it into a binary number
Problem: Decimal To Binary Converter
10
Input
1024
1010
Output
10000000000
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
Solution: Decimal To Binary Converter
Scanner scanner = new Scanner(System.in);
int decimal = Integer.valueOf(scanner.nextLine());
ArrayDeque<Integer> stack = new ArrayDeque<>();
// TODO: check if number is 0
while (decimal != 0)
stack.push(decimal % 2);
decimal /= 2;
while (!stack.isEmpty())
System.out.print(stack.pop());
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
 We are given an arithmetical expression with brackets (with nesting)
 Goal: extract all sub-expressions in brackets
Problem: Matching Brackets
1 + (2 - (2 + 3) * 4 / (3 + 1)) * 5
(2 + 3)
(3 + 1)
(2 - (2 + 3) * 4 / (3 + 1))
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
Solution: Matching Brackets (1)
Scanner scanner = new Scanner(System.in);
String expression = scanner.nextLine();
Deque<Integer> stack = new ArrayDeque<>();
// continue…
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
Solution: Matching Brackets (2)
for (int i = 0; i < expression.length(); i++) {
char ch = expression.charAt(i);
if (ch == '(')
stack.push(i);
else if (ch == ')')
int startIndex = stack.pop();
String contents =
expression.substring(startIndex, i + 1);
System.out.println(contents);
}
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
Queues
First In First Out (FIFO)
 First In First Out
Queue
26
210 5
 Queues provide the following functionality:
 Adding an element at the end of the queue
 Removing the first element from the queue
 Getting the first element of the queue without removing it
Queue – Abstract Data Type
210 5
210 5
210 5
 Creating a Queue
 Adding elements at the end of the queue
 add() – throws exception if queue is full
 offer() – returns false if queue is full
ArrayDeque<E> – Java Queue Implementation
ArrayDeque<Integer> queue = new ArrayDeque<>();
queue.add(element);
queue.offer(element);
 Removing elements
 remove() - throws exception if queue is empty
 poll() - returns null if queue is empty
 Check first element
ArrayDeque<E> – Java Queue Implementation (2)
element = queue.remove();
element = queue.poll();
element = queue.peek();
 Adds an element to the queue
add() / offer()
-315121
32104
5
size():Queue<Integer>
 Returns and removes first element
remove() / poll()
423
5
size():Queue<Integer>
-315121
 Children form a circle and pass a hot potato clockwise
 Every nth toss a child is removed until only one remains
 Upon removal the potato is passed forward
 Print the child that remains last
Problem: Hot Potato
Mimi Pepi Toshko
2
Input
Removed Pepi
Removed Mimi
Last is Toshko
Output
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
Solution: Hot Potato (1)
Scanner scanner = new Scanner(System.in);
String[] children = scanner.nextLine().split("s+");
int n = Integer.valueOf(scanner.nextLine());
ArrayDeque<String> queue = new ArrayDeque<>();
for (String child : children)
queue.offer(child);
// continue…
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
Solution: Hot Potato (2)
while (queue.size() > 1) {
for (int i = 1; i < n; i++)
queue.offer(queue.poll());
System.out.println("Removed " + queue.poll());
}
System.out.println("Last is " + queue.poll());
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
 Utility Methods
 peek() - checks the value of the first element
 size() - returns queue size
 toArray() - converts the queue to an array
 contains() - checks if element is in the queue
ArrayDeque<E> – Java Queue Implementation (3)
Integer element = queue.peeк();
Integer size = queue.size();
Integer[] arr = queue.toArray();
boolean exists = queue.contains(element);
 Gets the first element without removing it
peek()
1515
2size():Queue<Integer>
121
 Rework the previous problem so that a child is removed only on
a prime cycle (cycles start from 1)
 If a cycle is not prime, just print the child's name
Problem: Math Potato
Mimi Pepi Toshko
2
Input
Removed Pepi
Prime Mimi
Prime Toshko
Removed Mimi
Last is Toshko
Output
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
Solution: Math Potato
int cycle = 1;
while (queue.size() > 1) {
for (int i = 1; i < n; i++)
queue.offer(queue.poll());
if (isPrime(cycle))
System.out.println("Prime " + queue.peek());
else
System.out.println("Removed " + queue.poll());
cycle++;
}
System.out.println("Last is " + queue.poll());
Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
Queue – Overview of All Operations
5-315
4
121
012size():Queue<Integer>
5
3
15
peek() remove()add()
 Retains a specific order to the elements
 Higher priority elements are pushed to the
beginning of the queue
 Lower priority elements are pushed to the end of the queue
Priority Queue
AC B
 …
 …
 …
Summary
41
 Stack - Last In First Out (LIFO)
 push(), pop(), peek()
 Queue - First In First Out (FIFO)
 add(), poll(), peek()
 Priority Queue
 https://softuni.bg/modules/59/java-advanced
SoftUni Diamond Partners
SoftUni Organizational Partners
 Software University – High-Quality Education and
Employment Opportunities
 softuni.bg
 Software University Foundation
 http://softuni.foundation/
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University Forums
 forum.softuni.bg
Trainings @ Software University (SoftUni)
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-NonCom
mercial-ShareAlike 4.0 International" license
License
46
Ad

More Related Content

What's hot (20)

20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
Intro C# Book
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
Svetlin Nakov
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Chris Richardson
 
Lazy java
Lazy javaLazy java
Lazy java
Mario Fusco
 
Deep dive into Coroutines on JVM @ KotlinConf 2017
Deep dive into Coroutines on JVM @ KotlinConf 2017Deep dive into Coroutines on JVM @ KotlinConf 2017
Deep dive into Coroutines on JVM @ KotlinConf 2017
Roman Elizarov
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
Sunil OS
 
OOP V3.1
OOP V3.1OOP V3.1
OOP V3.1
Sunil OS
 
Java Queue.pptx
Java Queue.pptxJava Queue.pptx
Java Queue.pptx
vishal choudhary
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Sunil OS
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
Svetlin Nakov
 
3 searching algorithms in Java
3 searching algorithms in Java3 searching algorithms in Java
3 searching algorithms in Java
Mahmoud Alfarra
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFC
Sunil OS
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
07 java collection
07 java collection07 java collection
07 java collection
Abhishek Khune
 
How Hashmap works internally in java
How Hashmap works internally  in javaHow Hashmap works internally  in java
How Hashmap works internally in java
Ramakrishna Joshi
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
Intro C# Book
 
Socket programming
Socket programmingSocket programming
Socket programming
NemiRathore
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
Intro C# Book
 
Java string handling
Java string handlingJava string handling
Java string handling
GaneshKumarKanthiah
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
Manav Prasad
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
Intro C# Book
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
Svetlin Nakov
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Chris Richardson
 
Deep dive into Coroutines on JVM @ KotlinConf 2017
Deep dive into Coroutines on JVM @ KotlinConf 2017Deep dive into Coroutines on JVM @ KotlinConf 2017
Deep dive into Coroutines on JVM @ KotlinConf 2017
Roman Elizarov
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
Sunil OS
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Sunil OS
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
Svetlin Nakov
 
3 searching algorithms in Java
3 searching algorithms in Java3 searching algorithms in Java
3 searching algorithms in Java
Mahmoud Alfarra
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFC
Sunil OS
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
How Hashmap works internally in java
How Hashmap works internally  in javaHow Hashmap works internally  in java
How Hashmap works internally in java
Ramakrishna Joshi
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
Intro C# Book
 
Socket programming
Socket programmingSocket programming
Socket programming
NemiRathore
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
Intro C# Book
 

Similar to 16. Java stacks and queues (20)

Introduzione al TDD
Introduzione al TDDIntroduzione al TDD
Introduzione al TDD
Andrea Francia
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Arnaud Joly
 
[ROOTCON13] Pilot Study on Semi-Automated Patch Diffing by Applying Machine-L...
[ROOTCON13] Pilot Study on Semi-Automated Patch Diffing by Applying Machine-L...[ROOTCON13] Pilot Study on Semi-Automated Patch Diffing by Applying Machine-L...
[ROOTCON13] Pilot Study on Semi-Automated Patch Diffing by Applying Machine-L...
Asuka Nakajima
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
franciscoortin
 
DSA 103 Object Oriented Programming :: Week 3
DSA 103 Object Oriented Programming :: Week 3DSA 103 Object Oriented Programming :: Week 3
DSA 103 Object Oriented Programming :: Week 3
Ferdin Joe John Joseph PhD
 
Java practical
Java practicalJava practical
Java practical
william otto
 
Queue in Data Structure
Queue in Data StructureQueue in Data Structure
Queue in Data Structure
Muhazzab Chouhadry
 
object oriented programming lab manual .docx
object oriented programming  lab manual .docxobject oriented programming  lab manual .docx
object oriented programming lab manual .docx
Kirubaburi R
 
Ds lab manual by s.k.rath
Ds lab manual by s.k.rathDs lab manual by s.k.rath
Ds lab manual by s.k.rath
SANTOSH RATH
 
05-stack_queue.ppt
05-stack_queue.ppt05-stack_queue.ppt
05-stack_queue.ppt
Sarojkumari55
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
Vaclav Pech
 
Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018
Codemotion
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
J On The Beach
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
Nicola Pedot
 
A Deep Dive into Structured Streaming in Apache Spark
A Deep Dive into Structured Streaming in Apache Spark A Deep Dive into Structured Streaming in Apache Spark
A Deep Dive into Structured Streaming in Apache Spark
Anyscale
 
DSA 103 Object Oriented Programming :: Week 4
DSA 103 Object Oriented Programming :: Week 4DSA 103 Object Oriented Programming :: Week 4
DSA 103 Object Oriented Programming :: Week 4
Ferdin Joe John Joseph PhD
 
Appium TestNG Framework and Multi-Device Automation Execution
Appium TestNG Framework and Multi-Device Automation ExecutionAppium TestNG Framework and Multi-Device Automation Execution
Appium TestNG Framework and Multi-Device Automation Execution
pCloudy
 
computer notes - Data Structures - 9
computer notes - Data Structures - 9computer notes - Data Structures - 9
computer notes - Data Structures - 9
ecomputernotes
 
Java Language fundamental
Java Language fundamentalJava Language fundamental
Java Language fundamental
Infoviaan Technologies
 
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learnNumerical tour in the Python eco-system: Python, NumPy, scikit-learn
Numerical tour in the Python eco-system: Python, NumPy, scikit-learn
Arnaud Joly
 
[ROOTCON13] Pilot Study on Semi-Automated Patch Diffing by Applying Machine-L...
[ROOTCON13] Pilot Study on Semi-Automated Patch Diffing by Applying Machine-L...[ROOTCON13] Pilot Study on Semi-Automated Patch Diffing by Applying Machine-L...
[ROOTCON13] Pilot Study on Semi-Automated Patch Diffing by Applying Machine-L...
Asuka Nakajima
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
franciscoortin
 
object oriented programming lab manual .docx
object oriented programming  lab manual .docxobject oriented programming  lab manual .docx
object oriented programming lab manual .docx
Kirubaburi R
 
Ds lab manual by s.k.rath
Ds lab manual by s.k.rathDs lab manual by s.k.rath
Ds lab manual by s.k.rath
SANTOSH RATH
 
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0Binary Studio Academy: Concurrency in C# 5.0
Binary Studio Academy: Concurrency in C# 5.0
Binary Studio
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
Vaclav Pech
 
Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018
Codemotion
 
A Deep Dive into Structured Streaming in Apache Spark
A Deep Dive into Structured Streaming in Apache Spark A Deep Dive into Structured Streaming in Apache Spark
A Deep Dive into Structured Streaming in Apache Spark
Anyscale
 
Appium TestNG Framework and Multi-Device Automation Execution
Appium TestNG Framework and Multi-Device Automation ExecutionAppium TestNG Framework and Multi-Device Automation Execution
Appium TestNG Framework and Multi-Device Automation Execution
pCloudy
 
computer notes - Data Structures - 9
computer notes - Data Structures - 9computer notes - Data Structures - 9
computer notes - Data Structures - 9
ecomputernotes
 
Ad

More from Intro C# Book (20)

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
Intro C# Book
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
Intro C# Book
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
Intro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
Intro C# Book
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
Intro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
Intro C# Book
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
Intro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
Intro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
Intro C# Book
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
Intro C# Book
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
Intro C# Book
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
Intro C# Book
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
Intro C# Book
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
Intro C# Book
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
Intro C# Book
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
Intro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
Intro C# Book
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
Intro C# Book
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
Intro C# Book
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
Intro C# Book
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
Intro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
Intro C# Book
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
Intro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
Intro C# Book
 
19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity19. Java data structures algorithms and complexity
19. Java data structures algorithms and complexity
Intro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
Intro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
Intro C# Book
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
Intro C# Book
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
Intro C# Book
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
Intro C# Book
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
Intro C# Book
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
Intro C# Book
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
Intro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
Intro C# Book
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
Intro C# Book
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
Ad

Recently uploaded (19)

Determining Glass is mechanical textile
Determining  Glass is mechanical textileDetermining  Glass is mechanical textile
Determining Glass is mechanical textile
Azizul Hakim
 
DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)
APNIC
 
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 SupportReliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
steve198109
 
(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security
aluacharya169
 
IT Services Workflow From Request to Resolution
IT Services Workflow From Request to ResolutionIT Services Workflow From Request to Resolution
IT Services Workflow From Request to Resolution
mzmziiskd
 
Understanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep WebUnderstanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep Web
nabilajabin35
 
OSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description fOSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description f
cbr49917
 
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHostingTop Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
steve198109
 
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry SweetserAPNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC
 
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC
 
project_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptxproject_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptx
redzuriel13
 
White and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptxWhite and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptx
canumatown
 
Perguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolhaPerguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolha
socaslev
 
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation TemplateSmart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
yojeari421237
 
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
DataProvider1
 
highend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptxhighend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptx
elhadjcheikhdiop
 
Best web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you businessBest web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you business
steve198109
 
5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx
andani26
 
Computers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers NetworksComputers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers Networks
Tito208863
 
Determining Glass is mechanical textile
Determining  Glass is mechanical textileDetermining  Glass is mechanical textile
Determining Glass is mechanical textile
Azizul Hakim
 
DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)
APNIC
 
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 SupportReliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
steve198109
 
(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security
aluacharya169
 
IT Services Workflow From Request to Resolution
IT Services Workflow From Request to ResolutionIT Services Workflow From Request to Resolution
IT Services Workflow From Request to Resolution
mzmziiskd
 
Understanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep WebUnderstanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep Web
nabilajabin35
 
OSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description fOSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description f
cbr49917
 
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHostingTop Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
steve198109
 
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry SweetserAPNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC
 
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC
 
project_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptxproject_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptx
redzuriel13
 
White and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptxWhite and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptx
canumatown
 
Perguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolhaPerguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolha
socaslev
 
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation TemplateSmart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
yojeari421237
 
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
DataProvider1
 
highend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptxhighend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptx
elhadjcheikhdiop
 
Best web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you businessBest web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you business
steve198109
 
5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx
andani26
 
Computers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers NetworksComputers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers Networks
Tito208863
 

16. Java stacks and queues

  • 1. Stack and Queue Software University http://softuni.bg SoftUni Team Technical Trainers
  • 2. Table of Contents 1. Stack - Last In First Out (LIFO) • Stack Functionality • Java Stack Implementation • Overview of All Operations 2. Queue - First In First Out (FIFO) • Queue Functionality • Java Stack Implementation • Overview of All Operations 3. Priority Queue
  • 4.  Describes performance of particular algorithm  Runtime and memory consumption based on the input size N  We usually care about the worst-case performance  We measure the complexity as the Big O notation  Numerical function depending on the input size O(N)  We measure time as the number of simple steps  We measure memory as input data N by it's type size Algorithmic Complexity
  • 5.  O(1) – Constant time – time does not depend on N  O(log(N)) – Logarithmic time – grows with rate as log(N)  O(N) – Linear time grows at the same rate as N  O(N^2),O(N^3) – Quadratic, Cubic grows as square or cube of N  O(2^N) – Exponential grows as N becomes the exponent worst algorithmic complexity  For input size of 10 - 1024 steps  For input size of 100 – 1267650600228229401496703205376 steps  http://bigocheatsheet.com/ Algorithmic Complexity
  • 6.  Calculate maximum steps to find sum of even elements in an array  Assume that a single step is a single CPU instruction:  assignments, array lookups, comparisons, arithmetic operations Get Sum Number of Steps int getSumEven(int[] array) { int sum = 0; for (int i = 0; i < array.length; i++) if (array[i] % 2 == 0) sum += array[i]; return sum; } Solution: T(n) = 9n + 3 Counting maximum steps is called worst-case analysis
  • 7.  Worst-case  An upper bound on the running time  Average-case  Average running time  Best-case  The lower bound on the running time (the optimal case) Time Complexity
  • 8.  Why don't use Stack and Queue?  Implementation details which make unsecure usability  In many cases those structures will decrease the performance  Why to use ArrayDeque?  Implementation which makes the structure more secure  Better performance and usability  Methods which operate as those structures suggest Stacks And Queue vs. ArrayDeque
  • 9. Stack Last In First Out (LIFO)
  • 10.  Stacks provide the following functionality:  Pushing an element at the top of the stack  Popping element from the top fo the stack  Getting the topmost element without removing it Stack Functionality 2 10 5 2 10 5 2 10 5 Push Pop Peek
  • 11. ArrayDeque<E> – Java Stack Implementation  Creating a Stack  Adding elements at the top of the stack  Removing elements  Getting the value of the topmost element stack.push(element); ArrayDeque<Integer> stack = new ArrayDeque<>(); Integer element = stack.pop(); Integer element = stack.peek();
  • 12. Stack – Utility Methods ArrayDeque<Integer> stack = new ArrayDeque<>(); int size = stack.size(); boolean isEmpty = stack.isEmpty(); boolean exists = stack.contains(2);
  • 13. 012 5 3 210515 13 Stack – Overview of All Operations size(): 5 -7 45 132 push() pop() peek() Stack<Integer>
  • 14.  Write a program which takes 2 types of browser instructions:  Normal navigation: a URL is set, given by a string  The string "back" that sets the current URL to the last set URL Problem: Browser History https//softuni.bg/ back https//softuni.bg/trainings/courses back https//softuni.bg/trainings/2056 back https//softuni.bg/trainings/live https//softuni.bg/trainings/live/details Home Input https//softuni.bg/ no previous URLs https//softuni.bg/trainings/courses https//softuni.bg/ https//softuni.bg/trainings/2056 https//softuni.bg/ https//softuni.bg/trainings/live https//softuni.bg/trainings/live/details Output
  • 15. Scanner scanner = new Scanner(System.in); ArrayDeque<String> browser = new ArrayDeque<>(); String line = scanner.nextLine(); String current = ""; // continue… Solution: Browser History (1) Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 16. while(!line.equals("Home")) { if(line.equals("back")) { if(!browser.isEmpty()) {current = browser.pop(); } else { System.out.println("no previous URLs"); line = scanner.nextLine(); continue;} } else { if(!current.equals("")) { browser.push(current); } current = line; } System.out.println(current); line = scanner.nextLine(); } Solution: Browser History (2)
  • 17.  Implement a simple calculator that can evaluate simple expressions (only addition and subtraction) Problem: Simple Calculator 2 + 5 + 10 - 2 - 1 Input 2 - 2 + 5 14 Output 5 Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 18. Solution: Simple Calculator (1) Scanner scanner = new Scanner(System.in); String[] tokens = scanner.nextLine().split("s+"); Deque<String> stack = new ArrayDeque<>(); Collections.addAll(stack, tokens); // continues… Split by regex Adds a collection to another collection Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 19. Solution: Simple Calculator (2) while (stack.size() > 1) { int first = Integer.valueOf(stack.pop()); String op = stack.pop(); int second = Integer.valueOf(stack.pop()); switch (op) case "+": stack.push(String.valueOf(first + second)); break; case "-": stack.push(String.valueOf(first - second)); break; } System.out.println(stack.pop()); Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 20.  Create a converter which takes a decimal number and converts it into a binary number Problem: Decimal To Binary Converter 10 Input 1024 1010 Output 10000000000 Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 21. Solution: Decimal To Binary Converter Scanner scanner = new Scanner(System.in); int decimal = Integer.valueOf(scanner.nextLine()); ArrayDeque<Integer> stack = new ArrayDeque<>(); // TODO: check if number is 0 while (decimal != 0) stack.push(decimal % 2); decimal /= 2; while (!stack.isEmpty()) System.out.print(stack.pop()); Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 22.  We are given an arithmetical expression with brackets (with nesting)  Goal: extract all sub-expressions in brackets Problem: Matching Brackets 1 + (2 - (2 + 3) * 4 / (3 + 1)) * 5 (2 + 3) (3 + 1) (2 - (2 + 3) * 4 / (3 + 1)) Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 23. Solution: Matching Brackets (1) Scanner scanner = new Scanner(System.in); String expression = scanner.nextLine(); Deque<Integer> stack = new ArrayDeque<>(); // continue… Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 24. Solution: Matching Brackets (2) for (int i = 0; i < expression.length(); i++) { char ch = expression.charAt(i); if (ch == '(') stack.push(i); else if (ch == ')') int startIndex = stack.pop(); String contents = expression.substring(startIndex, i + 1); System.out.println(contents); } Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 25. Queues First In First Out (FIFO)
  • 26.  First In First Out Queue 26 210 5
  • 27.  Queues provide the following functionality:  Adding an element at the end of the queue  Removing the first element from the queue  Getting the first element of the queue without removing it Queue – Abstract Data Type 210 5 210 5 210 5
  • 28.  Creating a Queue  Adding elements at the end of the queue  add() – throws exception if queue is full  offer() – returns false if queue is full ArrayDeque<E> – Java Queue Implementation ArrayDeque<Integer> queue = new ArrayDeque<>(); queue.add(element); queue.offer(element);
  • 29.  Removing elements  remove() - throws exception if queue is empty  poll() - returns null if queue is empty  Check first element ArrayDeque<E> – Java Queue Implementation (2) element = queue.remove(); element = queue.poll(); element = queue.peek();
  • 30.  Adds an element to the queue add() / offer() -315121 32104 5 size():Queue<Integer>
  • 31.  Returns and removes first element remove() / poll() 423 5 size():Queue<Integer> -315121
  • 32.  Children form a circle and pass a hot potato clockwise  Every nth toss a child is removed until only one remains  Upon removal the potato is passed forward  Print the child that remains last Problem: Hot Potato Mimi Pepi Toshko 2 Input Removed Pepi Removed Mimi Last is Toshko Output Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 33. Solution: Hot Potato (1) Scanner scanner = new Scanner(System.in); String[] children = scanner.nextLine().split("s+"); int n = Integer.valueOf(scanner.nextLine()); ArrayDeque<String> queue = new ArrayDeque<>(); for (String child : children) queue.offer(child); // continue… Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 34. Solution: Hot Potato (2) while (queue.size() > 1) { for (int i = 1; i < n; i++) queue.offer(queue.poll()); System.out.println("Removed " + queue.poll()); } System.out.println("Last is " + queue.poll()); Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 35.  Utility Methods  peek() - checks the value of the first element  size() - returns queue size  toArray() - converts the queue to an array  contains() - checks if element is in the queue ArrayDeque<E> – Java Queue Implementation (3) Integer element = queue.peeк(); Integer size = queue.size(); Integer[] arr = queue.toArray(); boolean exists = queue.contains(element);
  • 36.  Gets the first element without removing it peek() 1515 2size():Queue<Integer> 121
  • 37.  Rework the previous problem so that a child is removed only on a prime cycle (cycles start from 1)  If a cycle is not prime, just print the child's name Problem: Math Potato Mimi Pepi Toshko 2 Input Removed Pepi Prime Mimi Prime Toshko Removed Mimi Last is Toshko Output Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 38. Solution: Math Potato int cycle = 1; while (queue.size() > 1) { for (int i = 1; i < n; i++) queue.offer(queue.poll()); if (isPrime(cycle)) System.out.println("Prime " + queue.peek()); else System.out.println("Removed " + queue.poll()); cycle++; } System.out.println("Last is " + queue.poll()); Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab
  • 39. Queue – Overview of All Operations 5-315 4 121 012size():Queue<Integer> 5 3 15 peek() remove()add()
  • 40.  Retains a specific order to the elements  Higher priority elements are pushed to the beginning of the queue  Lower priority elements are pushed to the end of the queue Priority Queue AC B
  • 41.  …  …  … Summary 41  Stack - Last In First Out (LIFO)  push(), pop(), peek()  Queue - First In First Out (FIFO)  add(), poll(), peek()  Priority Queue
  • 45.  Software University – High-Quality Education and Employment Opportunities  softuni.bg  Software University Foundation  http://softuni.foundation/  Software University @ Facebook  facebook.com/SoftwareUniversity  Software University Forums  forum.softuni.bg Trainings @ Software University (SoftUni)
  • 46.  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution-NonCom mercial-ShareAlike 4.0 International" license License 46