CS341 StacksQueues
CS341 StacksQueues
QUEUES
CS341_Data structures-Linear
Sophomores, HEC2
Fall24
Stacks
• Objects can only be retrieved in reverse order as
added
• Last-In, First-Out ("LIFO") push pop, peek
• Elements are stored in order of insertion (Plates,
Books, products)
• We do not think of them as having indexes.
• Client can only add/remove/examine
the last element added (the "top").
• Undo/Redo in text editors
• Recursion return var
method3 local vars
parameters
stack
return var
CS341
method2 local vars
parameters 2
return var
method1 local vars
parameters
Stacks operations
CS341 3
Stack<E>() constructs a new stack with
elements of type E
push(value) places given value on top of stack
pop() removes top value from stack and Class Stack
Stack<Integer> s = new
returns it;
throws EmptyStackException if Stack<Integer>();
stack is empty s.push(42);
peek() returns top value from stack s.push(-3);
without removing it;
throws EmptyStackException if s.push(17);
stack is empty System.out.println(s.pop());
size() returns number of elements in
stack
• Stack has other methods
isEmpty() returns true if stack has no which are inherited from
elements class java.util.Vector
CS341 • Stack.capacity()??? 4
Stack limitations/idioms
• You cannot loop over a stack in the usual common idiom: Pop each
way. element until the stack is empty.
Stack<Integer> s = new Stack<Integer>(); // process (and destroy) an entire stack
... while (!s.isEmpty()) {
do something with s.pop();
for (int i = 0; i < s.size(); i++) { }
do something with s.get(i);
}
CS341 5
What happened to my stack?
• Suppose we're asked to write a method max that accepts a Stack of integers and
returns the largest integer in the stack.
• The following solution is seemingly correct:
// Precondition: s.size() > 0
public static void max(Stack<Integer> s) {
int maxValue = s.pop();
while (!s.isEmpty()) {
int next = s.pop();
maxValue = Math.max(maxValue, next);
}
return maxValue;}
•
6
TheCS341
algorithm is correct, but what is wrong with the code?
public static void max(Stack<Integer> s) {
Stack<Integer> backup = new
Stack<Integer>();
int maxValue = s.pop();
backup.push(maxValue);
What
while (!s.isEmpty()) {
int next = s.pop();
happened to
backup.push(next); my stack?
maxValue = Math.max(maxValue, next);
The code destroys the
} stack in figuring out its
while (!backup.isEmpty()) { answer.
s.push(backup.pop()); } To fix this, you must
save and restore the
return maxValue;}
CS341
stack's contents 7
Stack overflow
• The most common cause for the JVM to encounter this situation is
▪Unterminated/infinite recursion,
▪Calling methods from within methods until the stack is exhausted
(Cyclic dependency between classes)
▪Having a vast number of local variables inside a method.
When stack memory is full, Java runtime throws
java.lang.StackOverFlowError whereas if heap memory is full, it throws
java.lang.OutOfMemoryError: Java Heap Space error.
Solution:CS341increase the stack size. Depending on the JVM installed, the8
default stack size could vary
Heap vs Stack Memory
public class Memory {
public static void main(String[] args) { // Line 1
int i=1; // Line 2
Object obj = new Object(); // Line 3
Memory mem = new Memory(); // Line 4
mem.foo(obj); // Line 5
} // Line 9
private void foo(Object param) { // Line 6
String str = param.toString(); //// Line 7
System.out.println(str); } // Line 8} 9
Stack underflow
• An error that occurs when we try to remove an element from the empty stack.
• Example : Exercise 5.
• PS: (3*4)/5)
CS341 10
Implementing Stack (Array)
ArrayStack<>
State : Big ‘O’ analysis
Data Push
Size()
Behavior: Pop
Push: Peek
Pop: Size
Peek:
Size: isEmpty
isEmpty:
CS341 11
Implementing Stack (LinkedList)
ArrayStack<>
State : Big ‘O’ analysis
Node top Push
Size()
Behavior: Pop
Push: Peek
Pop: Size
Peek:
Size: isEmpty
isEmpty:
CS341 12
Queues
• queue: Retrieves elements in the order they were added.
• First-In, First-Out ("FIFO")
• Elements are stored in order of
insertion but don't have indexes.
• Client can only add to the end of the
queue, and can only examine/remove
the front of the queue.
• basic queue operations:
• add (enqueue): Add an element to the back.
• remove (dequeue): Remove the front element.
• peek: Examine the front element.
CS341 13
Queues in computer science
• Operating systems:
• queue of print jobs to send to the printer
• queue of programs / processes to be run
• queue of network data packets to send
• Programming:
• modeling a line of customers or clients
• storing a queue of computations to be performed in order
• Real world examples:
• people on an escalator or waiting in a line
• cars at a gas station (or on an assembly line)
CS341 14
Queues
QUEUE IS AN INTERFACE AND
NOT A CLASS
CS341 15
Programming with Queues
add(value) places given value at back of queue Queue<Integer> q =
new
Offer(value) places given value at back of queue LinkedList<Integer>
remove() removes value from front of queue and returns it; ();
throws a NoSuchElementException if queue is q.add(42);
empty q.add(-3);
Poll() removes value from front of queue and returns it; q.add(17);
Null if empty System.out.println(q.
peek() returns front value from queue without removing it; remove());
returns null if queue is empty • IMPORTANT: When
size() returns number of elements in queue constructing a queue you
isEmpty() returns true if queue has no elements must use a new
LinkedList object
CS341 instead of a new Queue
16
object.
Implementing Queue (Array)
ArrayStack<>
State : Big ‘O’ analysis
Data remove
Size()
Behavior: Peek
add: add
remove: Size
Peek:
Size: isEmpty
isEmpty:
CS341 17
Implementing Queue (LinkedList)
ArrayStack<>
State : Big ‘O’ analysis
Data remove
Size()
Behavior: Peek
add: add
remove: Size
Peek:
Size: isEmpty
isEmpty:
CS341 18
Please download and install the Slido
app on all computers you use
CS341 19
What does the following code fragment print when n is 50? Give a high-
level description of what it does when presented with a positive integer n.
Stack<Integer> s = new
Stack<Integer>();
while (n > 0) {
s.push(n % 2);
n = n / 2;}
while (!s.isEmpty())
System.out.print(s.pop());
System.out.println();
CS341 20
Please download and install the Slido
app on all computers you use
CS341 21
CS341 22
Sorting Algorithm-Shell Sort
https://www.youtube.com/watch?v=IViqgakt-Eg
CS341 23