Java Advanced Stacks and Queues
Java Advanced Stacks and Queues
SoftUni Team
Technical Trainers
Software University
http://softuni.bg
Table of Contents
sli.do
#java-advanced
Algorithmic Complexity
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 al-
gorithmic complexity
For input size of 10 - 1024 steps
For input size of 100 – 1267650600228229401496703205376 steps
http://bigocheatsheet.com/
Get Sum Number of Steps
Calculate maximum steps to find sum of even elements in an array
int getSumEven(int[] array) { Solution:
int sum = 0; T(n) = 9n + 3
for (int i = 0; i < array.length; i++)
if (array[i] % 2 == 0) sum += array[i];
return sum;
}
Counting maximum steps is
called worst-case analysis
Assume that a single step is a single CPU instruction:
assignments, array lookups, comparisons, arithmetic operations
Time Complexity
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)
Stacks And Queue vs. ArrayDeque
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
Stack
Last In First Out (LIFO)
Stack Functionality
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
10 10 10
5 5 5
2 2 2
Push Pop Peek
ArrayDeque<E> – Java Stack Implementation
Creating a Stack
ArrayDeque<Integer> stack = new ArrayDeque<>();
Adding elements at the top of the stack
stack.push(element);
Removing elements
Integer element = stack.pop();
Getting the value of the topmost element
Integer element = stack.peek();
Stack – Utility Methods
132
10
15
-7
52
Stack<Integer>
push()
size(): 2
1
0
3
5
4
pop()
5
peek()
13
Problem: Browser History
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
Input Output
https//softuni.bg/ https//softuni.bg/
back no previous URLs
https//softuni.bg/trainings/courses https//softuni.bg/trainings/courses
back https//softuni.bg/
https//softuni.bg/trainings/2056 https//softuni.bg/trainings/2056
back https//softuni.bg/
https//softuni.bg/trainings/live https//softuni.bg/trainings/live
https//softuni.bg/trainings/live/details https//softuni.bg/trainings/live/details
Home
Solution: Browser History (1)
// continue…
Input Output
2 + 5 + 10 - 2 - 1 14
2 - 2 + 5 5
switch (op)
case "+": stack.push(String.valueOf(first + second));
break;
case "-": stack.push(String.valueOf(first - second));
break;
}
System.out.println(stack.pop());
Input Output
10 1010
1024 10000000000
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
Problem: Matching Brackets
We are given an arithmetical expression with brackets (with nesting)
Goal: extract all sub-expressions in brackets
1 + (2 - (2 + 3) * 4 / (3 + 1)) * 5
(2 + 3)
(3 + 1)
(2 - (2 + 3) * 4 / (3 + 1))
// continue…
10 5 2
26
Queue – Abstract Data Type
Queues provide the following functionality:
Adding an element at the end of the queue
10 5 2
Creating a Queue
ArrayDeque<Integer> queue = new ArrayDeque<>();
Adding elements at the end of the queue
queue.add(element);
queue.offer(element);
Removing elements
element = queue.remove();
element = queue.poll();
remove() - throws exception if queue is empty
poll() - returns null if queue is empty
Check first element
element = queue.peek();
add() / offer()
Adds an element to the queue
Queue<Integer> size(): 43
2
0
1
121
15
-3
5
remove() / poll()
Returns and removes first element
size(): 42
3
Queue<Integer>
121 15 -3 5
Problem: Hot Potato
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
Input Output
Mimi Pepi Toshko Removed Pepi
2 Removed Mimi
Last is Toshko
// continue…
Utility Methods
Integer element = queue.peeк();
Integer size = queue.size();
Integer[] arr = queue.toArray();
boolean exists = queue.contains(element);
size(): 2
Queue<Integer>
121 15
Problem: Math Potato
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
Input Output
Mimi Pepi Toshko Removed Pepi
2 Prime Mimi
Prime Toshko
Removed Mimi
Last is Toshko
if (isPrime(cycle))
System.out.println("Prime " + queue.peek());
else
System.out.println("Removed " + queue.poll());
cycle++;
}
System.out.println("Last is " + queue.poll());
size(): 4
2
1
0
3
Queue<Integer>
121
15
-3
5 5
C B A
Summary
Stack
… - Last In First Out (LIFO)
…push(), pop(), peek()
Queue
… - First In First Out (FIFO)
add(), poll(), peek()
Priority Queue
41
Questions?
https://softuni.bg/modules/59/java-advanced
SoftUni Diamond Partners
SoftUni Organizational Partners
Trainings @ Software University (SoftUni)
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
License
This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons
Attribution-NonCommercial-ShareAlike 4.0 International" li-
cense
46