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

11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classesIntro C# Book
 
Java if else condition - powerpoint persentation
Java if else condition - powerpoint persentationJava if else condition - powerpoint persentation
Java if else condition - powerpoint persentationManeesha Caldera
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVASURIT DATTA
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingNithyaN19
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritanceIntro C# Book
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
 
Collections Framework
Collections FrameworkCollections Framework
Collections FrameworkSunil OS
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and ClassesSvetlin Nakov
 
One dimensional 2
One dimensional 2One dimensional 2
One dimensional 2Rajendran
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and ArraysWebStackAcademy
 
Floyd warshall-algorithm
Floyd warshall-algorithmFloyd warshall-algorithm
Floyd warshall-algorithmMalinga Perera
 

What's hot (20)

11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
Java if else condition - powerpoint persentation
Java if else condition - powerpoint persentationJava if else condition - powerpoint persentation
Java if else condition - powerpoint persentation
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Data structures
Data structuresData structures
Data structures
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
 
Control statements in java programmng
Control statements in java programmngControl statements in java programmng
Control statements in java programmng
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Collections Framework
Collections FrameworkCollections Framework
Collections Framework
 
Python Lab Manual
Python Lab ManualPython Lab Manual
Python Lab Manual
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
 
One dimensional 2
One dimensional 2One dimensional 2
One dimensional 2
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
C# Overriding
C# OverridingC# Overriding
C# Overriding
 
Java operators
Java operatorsJava operators
Java operators
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
 
Floyd warshall-algorithm
Floyd warshall-algorithmFloyd warshall-algorithm
Floyd warshall-algorithm
 
Java threads
Java threadsJava threads
Java threads
 
Java exception
Java exception Java exception
Java exception
 

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.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
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arraysIntro 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.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
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
 
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

Moving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersMoving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersDamian Radcliffe
 
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607dollysharma2066
 
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on DeliveryCall Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Deliverybabeytanya
 
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...Diya Sharma
 
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service PuneVIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service PuneCall girls in Ahmedabad High profile
 
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girlsstephieert
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012rehmti665
 
Radiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girlsRadiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girlsstephieert
 
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With RoomVIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Roomgirls4nights
 
Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...
Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...
Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...Sheetaleventcompany
 
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...aditipandeya
 
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya Shirtrahman018755
 
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts servicesonalikaur4
 
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Delhi Call girls
 
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptxAWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptxellan12
 
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024APNIC
 

Recently uploaded (20)

Moving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersMoving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
 
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
 
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on DeliveryCall Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
Call Girls In Mumbai Central Mumbai ❤️ 9920874524 👈 Cash on Delivery
 
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
 
Rohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service PuneVIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
 
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
 
Radiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girlsRadiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girls
 
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With RoomVIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
 
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
 
Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...
Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...
Call Girls Service Chandigarh Lucky ❤️ 7710465962 Independent Call Girls In C...
 
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
VIP 7001035870 Find & Meet Hyderabad Call Girls Dilsukhnagar high-profile Cal...
 
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
 
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Porur Phone 🍆 8250192130 👅 celebrity escorts service
 
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
Best VIP Call Girls Noida Sector 75 Call Me: 8448380779
 
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
 
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptxAWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
 
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
 

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