0% found this document useful (0 votes)
11 views40 pages

CS211 5 Stacks

This document provides an overview of stacks, a linear Abstract Data Type (ADT) that operates on a Last-in-first-out (LIFO) principle, detailing its operations such as push, pop, peek, and size. It discusses the implementation of stacks using arrays and linked lists, highlighting the advantages and disadvantages of each method. Additionally, the document covers various applications of stacks, including expression evaluation, syntax parsing, and backtracking.

Uploaded by

d865629w2z
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views40 pages

CS211 5 Stacks

This document provides an overview of stacks, a linear Abstract Data Type (ADT) that operates on a Last-in-first-out (LIFO) principle, detailing its operations such as push, pop, peek, and size. It discusses the implementation of stacks using arrays and linked lists, highlighting the advantages and disadvantages of each method. Additionally, the document covers various applications of stacks, including expression evaluation, syntax parsing, and backtracking.

Uploaded by

d865629w2z
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Algorithms & Data Structures

CS211

Stacks

Lecture 10

Samar Alsaleh
Spring 2022
04

03 Finishing Thoughts
Summary & resources

02 Stacks Analysis
Computational complexity of stacks

Today’s 01 Stacks Implementation


Implementing stacks via arrays and linked lists

Agenda Introduction to Stacks


Intro to stacks ADT and their applications
Today’s 01

Agenda Introduction to Stacks


Intro to stacks ADT and their applications
Stacks Data Structure
- A stack is a linear Abstract Data Type (ADT), commonly used in most
programming languages to help solve many types of problems
- It is named stack as it behaves like a real-world stack,
- For example – a deck of cards, a pile of plates, or a stack of books etc.
- A real-world stack allows opera ons at one end only
- For example, we can place or remove a card or plate from the top of the
stack only, you can't reach into the middle!
- Likewise, Stack ADT allows all data opera ons at one end only
- At any given me, we can only access the top element of a stack
- This feature makes it LIFO data structure
- LIFO stands for Last-in-first-out
- That is, the last element to be put on a stack is the rst one to be removed
4
ti
ti
ti
fi
Stack Opera ons
- In stack terminology, inser on opera on is called
PUSH and removal opera on is called POP
- Stacks has the following two primary opera ons:
- push() − Add an element the top of the stack
- pop() − Remove the top element and return it
- To use a stack e ciently, we need to check the
status of stack as well
- For this purpose, the following func onality is
added to stacks:
- peek() − Get the top data element of the stack,
This diagram depicts a stack and its two without removing it
primary operations (Push, Pop)
- size() − Return the number of elements in the stack
- isEmpty() − Check if the stack is empty
5
ffi
ti
ti
ti
ti
ti
ti
Push Opera on

- 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

➔ Push takes an element


value as an input

➔ Pop returns an element


value as an output

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

push in : HAD push in :


CH
1. PUSH

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:

Traditional (infix) Expression Postfix Expression


15 − 8 15 8 −
(3 × 4 − (2 + 5)) × 4/2 34× 25 +− 4×2/

- 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

Today’s 01 Stacks Implementation


Implementing stacks via arrays and linked lists

Agenda Introduction to Stacks


Intro to stacks ADT and their applications
Stack Implementa ons
- A stack can be implemented by means of Arrays or Linked Lists
- Stack can either be a xed size one or it may have a sense of dynamic resizing
- In next implementa on, a stack is a container that extends the AbstractContainer
class and implements the Stack interface
- We will explore two stack implementa ons:
- StackAsArray
- The underlying data structure is an array object
- StackAsLinkedList
- The underlying data structure is a linked-list object
1 public interface Stack {
2 public Object peek();
3 public void push(Object obj);
4 public Object pop();
5 }
15
ti
fi
ti
ti
Implemen ng a Stack Using an Array
- Let's now explore our own implementa on of a stack, using an array as the underlying
structure in which we'll store the stack elements
- We'll have to take into account the possibility that the array could become full
- And remember that an array of objects really stores references to those objects
- An array of object references:

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:

-A er E is pushed onto the stack:

➔ 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:

- Stack a er 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

Today’s 01 Stacks Implementation


Implementing stacks via arrays and linked lists

Agenda Introduction to Stacks


Intro to stacks ADT and their applications
StackAsArray – push() Method
- push() method adds an element at the top the stack
- It takes as argument an Object to be pushed
- It rst checks if there is room le in the stack
- If no room is le , it throws a ContainerFullException excep on
- Otherwise, it puts the object into the array, and increments the top variable by one

1 public void push(Object object){


2 if (top == array.length-1)
3
4
5
else
throw new ContainerFullException();

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

1 public Object pop() {


2 if(top == -1)
3 throw new ContainerEmptyException();
4
5
6
else {
Object result = array[top--];
return result;
➡ Complexity: O(1)

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

1 public Object peek(){


2 if(top == -1)
3
4
5
else
throw new ContainerEmptyException();

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)

1 public Object pop() {


2 if(count == 0)
3 throw new ContainerEmptyException();
4 else{
5
6
7
Object obj = list.getFirst();
list.deleteFirst();
size--;
➡ Complexity: O(1)

8 return obj;
9 }
10 }

1 public Object peek() {


2 if(size == 0)
3
4
5
else
throw new ContainerEmptyException();

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

Today’s 01 Stacks Implementation


Implementing stacks via arrays and linked lists

Agenda Introduction to Stacks


Intro to stacks ADT and its applications
Comics Relief :)

“Who is putting the algorithms books in the horror section?” 36


Summary
Stack elements are processed in a LIFO manner—the last element in is the rst
element out.
The java.u l.Stack class has been part of the Java collec ons API.
A stack is the ideal data structure to use when evalua ng a pos ix expression.
The process of pu ng a new data element onto stack is known as PUSH
opera on.
Accessing the content while removing it from stack, is known as POP opera on.
The linked list implementa on has a simpler internal state and simpler codings
of its methods than the stack whose implementa on is based on an array.
It is easy to see that in the array list and linked list implementa ons, popping
and pushing are executed in constant me O(1). However, in the array list
implementa on, pushing an element onto a full stack requires alloca ng more
memory and copies the elements from the exis ng array list to a new array list.
Therefore, in the worst case, pushing takes O(n) me to nish.
37
ti
ti
ti
tti
ti
ti
ti
ti
ti
ti
ti
fi
ti
tf
ti
fi
ti
Resources & More…
Textbooks Chapters:
- Data Structures and Algorithms in Java, Ch4
- Data Structures and Algorithm Analysis in Java, Ch3
Interesting Articles & Videos:
- Introduction to Stack Data Structure (video)
- Stack Explained In Under 2 Minutes (video)
- ‫ ﺷﺮح اﻟـ‬stack - data structure (video)
- Stacks - Purposes, Implementations & Applications (article)
Credits:
- Some slides illustrative content is courtesy of
tutorialspoint.com
38
Resources & More…

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

You might also like