0% found this document useful (0 votes)
20 views

Java Advanced Stacks and Queues

The document discusses stacks, queues, and their implementations in Java. It begins by explaining that stacks follow the LIFO (last in, first out) principle while queues follow the FIFO (first in, first out) principle. It then provides details on using the ArrayDeque class to implement stacks and queues in Java, including the key methods like push(), pop(), peek(), add(), remove(), etc. Finally, it presents examples of problems that can be solved using stacks and queues and provides solutions using ArrayDeque.

Uploaded by

petrankapopova
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Java Advanced Stacks and Queues

The document discusses stacks, queues, and their implementations in Java. It begins by explaining that stacks follow the LIFO (last in, first out) principle while queues follow the FIFO (first in, first out) principle. It then provides details on using the ArrayDeque class to implement stacks and queues in Java, including the key methods like push(), pop(), peek(), add(), remove(), etc. Finally, it presents examples of problems that can be solved using stacks and queues and provides solutions using ArrayDeque.

Uploaded by

petrankapopova
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Stack and Queue

SoftUni Team
Technical Trainers
Software University
http://softuni.bg
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
Have a Question?

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

ArrayDeque<Integer> stack = new ArrayDeque<>();

int size = stack.size();


boolean isEmpty = stack.isEmpty();
boolean exists = stack.contains(2);
Stack – Overview of All Operations

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)

Scanner scanner = new Scanner(System.in);

ArrayDeque<String> browser = new ArrayDeque<>();


String line = scanner.nextLine();

String current = "";

// continue…

Check your solution here: https://judge.softuni.bg/Contests/1437/Stacks-and-Queues-Lab


Solution: Browser History (2)
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(); }
Problem: Simple Calculator
 Implement a simple calculator that can evaluate simple
expressions (only addition and subtraction)

Input Output

2 + 5 + 10 - 2 - 1 14

2 - 2 + 5 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<>(); Split by regex


Collections.addAll(stack, tokens);

// continues… 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


Problem: Decimal To Binary Converter
 Create a converter which takes a decimal number and
converts it into a binary number

Input Output

10 1010

1024 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
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))

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)
Queue
 First In First Out

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

 Removing the first element from the queue


10 5 2

 Getting the first element of the queue without removing it


10 5 2
ArrayDeque<E> – Java Queue Implementation

 Creating a Queue
ArrayDeque<Integer> queue = new ArrayDeque<>();
 Adding elements at the end of the queue
queue.add(element);
queue.offer(element);

 add() – throws exception if queue is full


 offer() – returns false if queue is full
ArrayDeque<E> – Java Queue Implementation (2)

 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

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


ArrayDeque<E> – Java Queue Implementation (3)

 Utility Methods
Integer element = queue.peeк();
Integer size = queue.size();
Integer[] arr = queue.toArray();
boolean exists = queue.contains(element);

 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
peek()
 Gets the first element without removing it

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

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

size(): 4
2
1
0
3
Queue<Integer>

121
15
-3
5 5

add() peek() remove()


Priority Queue
 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

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

You might also like