SlideShare a Scribd company logo
1 of 46
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

More Related Content

What's hot

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 traversalIntro C# Book
 
VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...
VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...
VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...Nithin Kumar,VVCE, Mysuru
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsSvetlin Nakov
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classesIntro C# Book
 
Head First Java Chapter 1
Head First Java Chapter 1Head First Java Chapter 1
Head First Java Chapter 1Tom Henricksen
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arraysIntro C# Book
 
Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]Muhammad Hammad Waseem
 
Linear Search Data Structure
Linear Search Data StructureLinear Search Data Structure
Linear Search Data StructureTalha Shaikh
 
Selection sort
Selection sortSelection sort
Selection sortJay Patel
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classesFajar Baskoro
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and OperatorsSunil OS
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory ManagementRahul Jamwal
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In JavaSpotle.ai
 
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | EdurekaWhat is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | EdurekaEdureka!
 

What's hot (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
 
VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...
VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...
VTU Design and Analysis of Algorithms(DAA) Lab Manual by Nithin, VVCE, Mysuru...
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
Head First Java Chapter 1
Head First Java Chapter 1Head First Java Chapter 1
Head First Java Chapter 1
 
Exception handling in python
Exception handling in pythonException handling in python
Exception handling in python
 
Stack and queue
Stack and queueStack and queue
Stack and queue
 
Java Arrays
Java ArraysJava Arrays
Java Arrays
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
 
String Handling
String HandlingString Handling
String Handling
 
Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]
 
Linear Search Data Structure
Linear Search Data StructureLinear Search Data Structure
Linear Search Data Structure
 
Selection sort
Selection sortSelection sort
Selection sort
 
Lect 1-java object-classes
Lect 1-java object-classesLect 1-java object-classes
Lect 1-java object-classes
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
 
Polymorphism In Java
Polymorphism In JavaPolymorphism In Java
Polymorphism In Java
 
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | EdurekaWhat is Dictionary In Python? Python Dictionary Tutorial | Edureka
What is Dictionary In Python? Python Dictionary Tutorial | Edureka
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Java operators
Java operatorsJava operators
Java operators
 

Similar to 16. Java stacks and queues

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-learnArnaud 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 8franciscoortin
 
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.rathSANTOSH 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.0Binary 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 fruitVaclav 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 2018Codemotion
 
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 ExecutionpCloudy
 
computer notes - Data Structures - 9
computer notes - Data Structures - 9computer notes - Data Structures - 9
computer notes - Data Structures - 9ecomputernotes
 

Similar to 16. Java stacks and queues (20)

Introduzione al TDD
Introduzione al TDDIntroduzione al TDD
Introduzione al TDD
 
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
 
[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...
 
New Functional Features of Java 8
New Functional Features of Java 8New Functional Features of Java 8
New Functional Features of Java 8
 
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
 
Java practical
Java practicalJava practical
Java practical
 
Queue in Data Structure
Queue in Data StructureQueue in Data Structure
Queue in Data Structure
 
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
 
05-stack_queue.ppt
05-stack_queue.ppt05-stack_queue.ppt
05-stack_queue.ppt
 
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
 
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
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
 
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
 
Lazy java
Lazy javaLazy java
Lazy java
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
 
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
 
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
 
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
 
computer notes - Data Structures - 9
computer notes - Data Structures - 9computer notes - Data Structures - 9
computer notes - Data Structures - 9
 
Java Language fundamental
Java Language fundamentalJava Language fundamental
Java Language fundamental
 

More from 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 CodeIntro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism Intro C# Book
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstractionIntro C# Book
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritanceIntro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro 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 complexityIntro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classesIntro C# Book
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processingIntro C# Book
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handlingIntro C# Book
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and ClassesIntro C# Book
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and MapsIntro 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 variablesIntro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with javaIntro C# Book
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem SolvingIntro C# Book
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQIntro C# Book
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming CodeIntro C# Book
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm ComplexityIntro C# Book
 

More from Intro C# Book (20)

Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
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
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
 
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...
 
02. Data Types and variables
02. Data Types and variables02. Data Types and variables
02. Data Types and variables
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming Code
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity
 

Recently uploaded

Trump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts SweatshirtTrump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts Sweatshirtrahman018755
 
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdfMatthew Sinclair
 
Mira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
Mira Road Housewife Call Girls 07506202331, Nalasopara Call GirlsMira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
Mira Road Housewife Call Girls 07506202331, Nalasopara Call GirlsPriya Reddy
 
Real Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirtReal Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirtrahman018755
 
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查ydyuyu
 
Russian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
Russian Escort Abu Dhabi 0503464457 Abu DHabi EscortsRussian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
Russian Escort Abu Dhabi 0503464457 Abu DHabi EscortsMonica Sydney
 
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge GraphsEleniIlkou
 
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...APNIC
 
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制pxcywzqs
 
一比一原版田纳西大学毕业证如何办理
一比一原版田纳西大学毕业证如何办理一比一原版田纳西大学毕业证如何办理
一比一原版田纳西大学毕业证如何办理F
 
Indian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi EscortsIndian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi EscortsMonica Sydney
 
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...gajnagarg
 
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency""Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency"growthgrids
 
APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53APNIC
 
Best SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency DallasBest SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency DallasDigicorns Technologies
 
Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...
Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...
Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...meghakumariji156
 
一比一原版奥兹学院毕业证如何办理
一比一原版奥兹学院毕业证如何办理一比一原版奥兹学院毕业证如何办理
一比一原版奥兹学院毕业证如何办理F
 
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrStory Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrHenryBriggs2
 
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime NagercoilNagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoilmeghakumariji156
 
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girlsRussian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girlsMonica Sydney
 

Recently uploaded (20)

Trump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts SweatshirtTrump Diapers Over Dems t shirts Sweatshirt
Trump Diapers Over Dems t shirts Sweatshirt
 
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
20240510 QFM016 Irresponsible AI Reading List April 2024.pdf
 
Mira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
Mira Road Housewife Call Girls 07506202331, Nalasopara Call GirlsMira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
Mira Road Housewife Call Girls 07506202331, Nalasopara Call Girls
 
Real Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirtReal Men Wear Diapers T Shirts sweatshirt
Real Men Wear Diapers T Shirts sweatshirt
 
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
 
Russian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
Russian Escort Abu Dhabi 0503464457 Abu DHabi EscortsRussian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
Russian Escort Abu Dhabi 0503464457 Abu DHabi Escorts
 
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
2nd Solid Symposium: Solid Pods vs Personal Knowledge Graphs
 
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
 
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
一比一原版(Offer)康考迪亚大学毕业证学位证靠谱定制
 
一比一原版田纳西大学毕业证如何办理
一比一原版田纳西大学毕业证如何办理一比一原版田纳西大学毕业证如何办理
一比一原版田纳西大学毕业证如何办理
 
Indian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi EscortsIndian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
Indian Escort in Abu DHabi 0508644382 Abu Dhabi Escorts
 
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
Top profile Call Girls In Dindigul [ 7014168258 ] Call Me For Genuine Models ...
 
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency""Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
 
APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53
 
Best SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency DallasBest SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency Dallas
 
Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...
Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...
Tadepalligudem Escorts Service Girl ^ 9332606886, WhatsApp Anytime Tadepallig...
 
一比一原版奥兹学院毕业证如何办理
一比一原版奥兹学院毕业证如何办理一比一原版奥兹学院毕业证如何办理
一比一原版奥兹学院毕业证如何办理
 
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrStory Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
 
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime NagercoilNagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
 
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girlsRussian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
 

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