CS211 5 Stacks
CS211 5 Stacks
CS211
Stacks
Lecture 10
Samar Alsaleh
Spring 2022
04
03 Finishing Thoughts
Summary & resources
02 Stacks Analysis
Computational complexity of stacks
- The process of pu ng a new data element onto stack is known as PUSH Opera on
- Push opera on involves series of steps:
- Step 1 − Check if the stack is full
- Step 2 − If the stack is full, produce error and exit
- Step 3 − If the stack is not full, increment top to point to the next empty space
- Step 4 − Add data element to the stack loca on, where top is poin ng
- Step 5 − Return success
6
ti
tti
ti
ti
ti
ti
Pop Opera on
- Accessing the content while removing it from the stack, is known as a Pop Opera on.
- Pop opera on involves series of steps:
- Step 1 − Check if the stack is empty
- Step 2 − If the stack is empty, produce error and exit
- Step 3 − If the stack is not empty, access the data element at which top is poin ng
- Step 4 − Decrease the value of top by 1
- Step 5 − Return success
7
ti
ti
ti
ti
Pushing and Popping a Stack
- The following is an illustra on of the pushing and popping elements in/out of a stack
8
ti
Pushing and Popping a Stack (cont.)
Example1: Reverse Spelling
- We can easily use a stack to reverse the spelling of a word
- If the program read in CHAD, then it will output DAHC
push in : CHAD push in :
C CHA
pop out : pop out : D
CH
2. POP
pop out : pop out :DA
push in : AD push in :
CHA C
pop out : pop out : DAH
push in : D push in :
CHAD .
pop out : pop out : DAHC
9
Pushing and Popping a Stack (cont.)
Example2: Pos ix Expressions
- Let's see how a stack can be used to help us solve the problem of evalua ng pos ix
expressions
- The way we are using to write expressions is known as in x nota on
- Another way is the Pos ix nota on
- A pos ix expression is wri en with the operator following the two operands instead of
between them, for example:
- Pos ix expressions eliminate the need for parentheses to specify the order of opera ons
10
tf
tf
tf
tf
tt
ti
fi
ti
ti
tf
ti
Pushing and Popping a Stack (cont.)
Example2: Pos ix Expressions
- We'll use a stack as follows to evaluate a pos ix expression:
- Scan the expression le to right
- When an operand is encountered, push it on the stack
- When an operator is encountered, pop the top two elements on the stack, perform the
opera on, then push the result on the stack
- When the expression is exhausted, the value in the stack is the nal result
- Here's how the stack changes as the following expression is evaluated:
7 4 −3 × 1 5 + / ×
- Recall that, operand1 is pushed rst and operand2 is popped rst
11
ti
tf
ft
fi
tf
fi
fi
Applica ons of Stacks
Stacks have numerous applica ons, including for example:
- Expression Evalua on
- Stack is used to evaluate pre x, pos ix and in x expressions.
- Expression Conversion
- Stack can be used to convert one form of expression to another (to and from pre x, pos ix
or in x nota on)
- Syntax Parsing
- Many compilers use a stack to parse the syntax of expressions, program blocks etc. before
transla ng into low level code.
- Backtracking
- Suppose we are nding a path for solving maze problem. We choose a path and a er
following it we realize that it is wrong. Now we need to go back to the beginning of the
path to start with new path. This can be done with the help of stack.
12
fi
ti
ti
ti
fi
ti
fi
ti
tf
fi
fi
ft
tf
Applica ons of Stacks (cont.)
Stacks have numerous applica ons, including for example:
- Parenthesis Checking
- Stack is used to check the proper opening and closing of parenthesis.
- String Reversal
- Stack is used to reverse a string. We push the characters of string one by one into stack and
then pop character from stack.
- Func on Call
- Stack is used to keep informa on about the ac ve func ons or subrou nes.
- Some other examples:
- Opera ons on long integers
- History of visited pages through a Web browser
- The undo sequence in a text editor
- Memory management
13
ti
ti
ti
ti
ti
ti
ti
ti
02
16
ti
ti
Implemen ng a Stack Using an Array (cont.)
- A stack with elements A, B, C, and D pushed on in that order:
-A er pushing element E:
-A er popping:
➔ Note: In an array implementa on of pop(), the data element is not actually removed,
instead top is decremented to a lower posi on in the stack to point to the next value
17
ft
ft
ti
ti
ti
Implemen ng a Stack Using an Array (cont.)
- The following methods represent the array implementa on of the stack opera ons:
Push() isFull()
1 public void push(int x) { 1 public boolean isFull() {
2 if( !isFull() ) { 2 if(top < size-1)
3 top++; 3 return false;
4 values[top] = x; 4 return true;
5 } 5 }
6 }
Pop() isEmpty()
1 public int pop() { 1 public boolean isEmpty() {
2 int retVal = 0 ; 2 if(top == -1)
3 if( !isEmpty() ) { 3 return true;
4 retVal= values[top]; 4 return false;
5 top--; 5 }
6 }
8 return retVal;
9 }
18
ti
ti
ti
Implemen ng a Stack Using an Array (cont.)
Managing Capacity:
- The number of cells in an array is its capacity
- It's not possible to change the capacity of an array in Java once it's been created
- Therefore, to expand the capacity of the stack, we'll create a new (larger) array and
copy over the elements
- This will happen infrequently, and the user of the stack need not worry about it
happening
19
ti
Implemen ng a Stack Using a Linked List
- One disadvantage of using an array to implement a stack is the wasted space
- Most of the me most of the array is unused
- A more elegant and economical implementa on of a stack uses a linked list, which is a
data structure that links together individual data objects as if they were “links” in a
“chain” of data
- Each me an object is pushed, a node is created, the object is inserted into a node,
and the node is linked to the front of the chain of nodes
- The linked list implementa
on has a simpler internal state and simpler coding of its
methods than the stack whose implementa on is based on an array
20
ti
ti
ti
ti
ti
ti
Implemen ng a Stack Using a Linked List (cont.)
- Since all acvity on a stack happens on one end, a single reference to the front (or the
rear, but not both) of the list will represent the top of the stack
21
ti
ti
Implemen ng a Stack Using a Linked List (cont.)
- The stack a er A, B, C, and D are pushed, in that order:
➔ Note: In a linked list implementa on pop() actually removes data element and
deallocates memory space
22
ft
ft
ti
ti
Implemen ng a Stack Using a Linked List (cont.)
- Another example:
- Stack before inser on:
23
ft
ti
ti
ti
Implemen ng a Stack Using a Linked List (cont.)
- Let's now implement our own version of a stack that uses a linked list to hold the
elements
- Our LinkedStack<T> class stores a generic type T and implements the same
StackADT<T> interface used previously
- We may use the LinkedList class found in java.util or use the class SLL (or DLL)
we have created before (recall the linked list classes we have implemented the
previous lectures)
- An integer count will store how many elements are currently in the stack
- Remember! In a stack, you always access one end for addi on and dele on
- Therefore, if you decide to use head end for inser on to push elements, you have to
use the same end for dele on to pop elements and vise-versa
24
ti
ti
ti
ti
ti
Implemen ng a Stack Using a Linked List (cont.)
Stack Node Class:
1 public class LinearNode<T> {
2 private LinearNode<T> next;
3 private T element;
4
5 public LinearNode() { //Create an empty node
6 next = null;
7 element = null;
8 }
9 public LinearNode(T elem) { //Create a node storing the specified element
10 next = null;
11 element = elem;
12 }
13 public LinearNode<T> getNext() { //Return the node that follows this one
14 return next;
15 }
16 public void setNext(LinearNode<T> node) { //Set the node that follows this one
17 next = node;
18 }
19 public T getElement() { //Return the element stored in this node
20 return element;
21 }
22 public void setElement(T elem) { //Set the element stored in this node
23 element = elem;
24 }
25 } 25
ti
Implemen ng a Stack Using a Linked List (cont.)
Stack Linked List Class:
1 public class LinkedStack<T> implements StackADT<T> {
2 private int count;
3 private LinearNode<T> top;
4
5 public LinkedStack() { //Create an empty stack
6 count = 0;
7 top = null;
8 }
9 public void push(T element) { //Add the specified element to the top of this stack
10 LinearNode<T> temp = new LinearNode<T>(element);
11 temp.setNext(top); //set the new node's 'next' reference to the front of the list
12 top = temp; //reset the front of the list
13 count++;
14 }
15 public T pop() throws EmptyCollectionException {
16 //Remove the element at the top of this stack and return a reference to it
17 if (isEmpty())
18 throw new EmptyCollectionException("stack");
19 T result = top.getElement();
20 top = top.getNext();
21 count--;
22 return result;
23 }
24 }
26
ti
Stacks in the Java API
- The java.util.Stack class has been part of the Java collec ons API since Java 1.0
- It implements the classic opera ons, without any separate interfaces de ned
27
ti
ti
fi
03
02 Stacks Analysis
Computational complexity of stacks
array[++top] = object;
➡ Complexity: O(1)
6 }
29
fi
ft
ft
ti
StackAsArray – pop() Method
- pop() method removes an item from the stack and returns that item
- It rst checks if the stack is empty
- If the stack is empty, it throws a ContainerEmptyException.
- Otherwise, it simply decreases top by one and returns the item found at the top of the
stack
7 }
8 }
30
fi
StackAsArray – peek() Method
- peek() method is a stack accessor which returns the top item in the stack without
removing that item
- It rst checks if the stack is empty
- If the stack is empty, it throws a ContainerEmptyException
- Otherwise, it returns the top item
return array[top];
➡ Complexity: O(1)
6 }
31
fi
StackAsLinkedList Implementa on
1 public void push(Object obj) {
2
3
4 }
list.insertFirst(obj);
size++; ➡ Complexity: O(1)
8 return obj;
9 }
10 }
return list.getFirst();
➡ Complexity: O(1)
6 }
32
ti
Sample Implementa ons - As Array List
1 public class Stack {
2 private java.util.ArrayList pool = new java.util.ArrayList();
3 public Stack() {
4 }
5 public Stack(int n) {
6 pool.ensureCapacity(n);
7 }
8 public void clear() {
9 pool.clear();
10 }
11 public boolean isEmpty() {
12 return pool.isEmpty();
13 }
14 public Object topEl() {
15 if (isEmpty())
16 throw new java.util.EmptyStackException();
17 return pool.lastElement();
18 }
19 public Object pop() {
20 if (isEmpty())
21 throw new java.util.EmptyStackException();
22 return pool.remove(pool.size()-1);
23 }
24 public void push(Object el) {
25 pool.add(el);
26 }
27 public String toString() {
28 return pool.toString();
29 }
30 } 33
ti
Sample Implementa ons - As Linked List
1 public class LLStack {
2 private java.util.LinkedList list = new java.util.LinkedList();
3 public LLStack() {
4 }
5 public void clear() {
6 list.clear();
7 }
8 public boolean isEmpty() {
9 return list.isEmpty();
10 }
11 public Object topEl() {
12 if (isEmpty())
13 throw new java.util.EmptyStackException();
14 return list.getLast();
15 }
16 public Object pop() {
17 if (isEmpty())
18 throw new java.util.EmptyStackException();
19 return list.removeLast();
20 }
21 public void push(Object el) {
22 list.addLast(el);
23 }
24 public String toString() {
25 return list.toStrung();
26 }
27 }
34
ti
04
03 Finishing Thoughts
Summary & resources
02 Stacks Analysis
Computational complexity of stacks
Other Resources:
- Java Software Structures - Designing and Using Data Structures,
4th edition, Lewis and Chase.
- Data Structures & Algorithms in Java, 3rd edition,
- Data Structures and Algorithm Analysis in Java, 3rd edition, Weiss
- Data Structures and Algorithms in Java, 6th edition, Goodrich,
Tamassia and Goldwasser.
- Slides at: http://faculty.kfupm.edu.sa/ICS/jauhar/ics202/
- https://www.tutorialspoint.com/data_structures_algorithms/
index.htm
39
Thank You & Stay Safe
:)