Slide 4
Slide 4
Slide 4
Fall 2024
• Stacks
Lecture Plan
2
Stacks
What is a Stack?
⮚ A stack is an example of a data structure
▪ A method of organizing data
Data Structures and Algorithms
Stacks Example
4
Stacks
⮚ Problem:
Data Structures and Algorithms
▪ What happens if we try to pop an item off the stack when the
stack is empty?
▪ This is called a stack underflow. The pop method needs some
way of telling us that this has happened.
5
Exceptions
⮚ In the Stack ADT, operations pop and top cannot be performed if the
stack is empty.
7
The stack operation
Data Structures and Algorithms
⮚ The stack operation creates an empty stack. The following shows the
format.
8
The push operation
Data Structures and Algorithms
⮚ The push operation inserts an item at the top of the stack. The following
shows the format.
9
9
The pop operation
Data Structures and Algorithms
⮚ The pop operation deletes the item at the top of the stack. The
following shows the format.
10
10
The empty operation
Data Structures and Algorithms
⮚ This operation returns true if the stack is empty and false if the stack is
not empty.
11
Example
12
Selecting storage structures
⮚ Two choices
Data Structures and Algorithms
13
Select position 0 as top of the stack
Data Structures and Algorithms
14
Select position 0 as bottom of the
stack
⮚ A better approach is to let position 0 be the bottom of the stack
Data Structures and Algorithms
16
Implementing a Stack
17
Implementing a Stack
either…
▪ Store the items in the stack in a linked list
▪ The top of the stack is the head node, the bottom of the stack
is the end of the list
▪ push by adding to the front of the list
▪ pop by removing from the front of the list
18
Stack (Array Implementation)
⮚ Algorithm for push:
Data Structures and Algorithms
this.maxSize = size;
this.stackArray = new
int[maxSize];
this.top = -1;
}
top++;
stackArray[top] = j;
}
}
if(isEmpty())
throw new IllegalArgumentException("Stack is
Empty!");
else{
System.out.println("Popping Out Elements From
Stack: ");
while (!isEmpty())
System.out.println(pop()+" ");
}
}
23
Stack (Linked List Implementation)
Data Structures and Algorithms
24
LinkedListStack Class Implementation
public class LinkedListStack {
public class Node { private Node first;
public int
data; public LinkedListStack(){
public Node this.first = null;
Data Structures and Algorithms
}
next;
// Push Method will add Node to the Beginning of the
} List
25
public int pop(){
if(first == null){
throw new NoSuchElementException("Stack is
empty!");
Data Structures and Algorithms
}
int value = first.data;
first = first.next;
return value;
}
26
PrintStack
if(isEmpty())
throw new IllegalArgumentException("Stack is
Empty!");
else{
System.out.println("Popping Out Elements From
Stack: ");
while (!isEmpty())
System.out.println(pop()+" ");
}
}
27
public int max(){
if(isEmpty())
throw new IllegalArgumentException("Stack is
Empty!");
else {
int max = first.data;
while (!isEmpty()) {
if (max < first.data)
max = first.data;
pop();
}
Data Structures and Algorithms
return max;
}
}
return product;
}
}
sum += first.data;
count++;
pop();
}
average = sum/count;
return average;
}
}
⮚ Direct applications
▪ Page-visited history in a Web browser
▪ Undo sequence in a text editor
▪ Chain of method calls in the Java Virtual Machine or C++
runtime environment
▪ Program execution
▪ Parsing
▪ Evaluating postfix expressions
⮚ Indirect applications
▪ Auxiliary data structure for algorithms
▪ Component of other data structures 31
Reversing data items
32
Pairing data items
34
Applications of Stacks
⮚ RECURSION
▪ Recursion occurs when a function is called by itself repeatedly; the
Data Structures and Algorithms
function is called recursive function. The general algorithm model for any
recursive function contains the following steps:
2. Body: If the base criterion has been reached, then perform the final
computation and go to step 3; otherwise, perform the partial
computation and go to step 1 (initiate a recursive call).
RECURSION
36
Data Structures and Algorithms
RECURSION Example
37
TOWER OF HANOI
• The initial setup of the problem is shown in next slide. Here three
pegs (or towers) X, Y and Z exists. There will be four different sized
Data Structures and Algorithms
disks, say A, B, C and D. Each disk has a hole in the center so that it
can be stacked on any of the pegs. At the beginning, the disks are
stacked on the X peg, that is the largest sized disk on the bottom and
the smallest sized disk on top as shown in Fig. 3.4.
• Tower of Hanoi is a mathematical puzzle invented by a French
Mathematician Edouard Lucas in 1883.
• The game starts by having few discs stacked in increasing order of
size. The number of discs can vary, but there are only three pegs.
38
Data Structures and Algorithms
TOWER OF HANOI
39
Data Structures and Algorithms
TOWER OF HANOI
40
Data Structures and Algorithms
TOWER OF HANOI
41
Data Structures and Algorithms
TOWER OF HANOI
42
Data Structures and Algorithms
TOWER OF HANOI
43
TOWER OF HANOI
⮚ Explicit Pattern
▪Number of Disks Number of Moves
Data Structures and Algorithms
1 1
2 3
3 7
4 15
5 31
46
EXPRESSION
⮚ 1. Infix notation
▪ The infix notation is what we come across in our general mathematics,
Data Structures and Algorithms
⮚ 3. Postfix notation
▪ In the postfix notation the operator(s) are written after the operands, so
Data Structures and Algorithms
48
EXPRESSION
⮚ The method of converting infix expression A + B * C to postfix form is:
A + B * C Infix Form
A + (B * C) Parenthesized expression
Data Structures and Algorithms
A + { [ (BC +) + (DE +) * F ] / G}
A + { [ (BC +) + (DE + F *] / G}
A + { [ (BC + (DE + F * +] / G} .
A + [ BC + DE + F *+ G / ]
[(AB + ) * C / D ] + [ (EA ^) / B ]
[(AB + ) * C / D ] + [ (EA ^) B / ]
[(AB + ) C * D / ] + [ (EA ^) B / ]
(AB + ) C * D / (EA ^) B / +
AB + C * D / EA ^ B / + Postfix Form
51
Algorithm
1. Push “(” onto stack, and add“)” to the end of P.
2. Scan P from left to right and repeat Steps 3 to 6 for each element of P until the
stack is empty.
Data Structures and Algorithms
Postfix String
Stack
▪ Next character scanned is 'b' which will be placed in the Postfix string. Next
character is '*' which is an operator. Now, the top element of the stack is '+'
which has lower precedence than '*', so '*' will be pushed to the stack.
Postfix String
Stack 53
Example 3
▪ The next character is 'c' which is placed in the Postfix string. Next character scanned is '-'. The
topmost character in the stack is '*' which has a higher precedence than '-'. Thus '*' will be popped
out from the stack and added to the Postfix string. Even now the stack is not empty. Now the
topmost element of the stack is '+' which has equal priority to '-'. So pop the '+' from the stack and
Data Structures and Algorithms
add it to the Postfix string. The '-' will be pushed to the stack.
Postfix String
Stack
▪ Next character is 'd' which is added to Postfix string. Now all characters have been scanned so we
must pop the remaining elements from the stack and add it to the Postfix string. At this stage we
have only a '-' in the stack. It is popped out and added to the Postfix string. So, after all characters
are scanned, this is how the stack and Postfix string will be :
Postfix String
54
Applications of Stacks
⮚ Consider the following arithmetic infix expression P
P=A+(B/C-(D*E^F)+G)*H
Data Structures and Algorithms
55
Advantages of Postfix
• 1. No Need for Parentheses
• 2. Simplifies Expression Evaluation
Data Structures and Algorithms
56
When is Prefix Notation Useful?
• Prefix notation does have some benefits in certain contexts,
particularly in functional programming or where recursion is a natural
Data Structures and Algorithms
57
• Postfix notation is generally preferred over prefix because:
• It is easier to evaluate using a stack with simple left-to-right
Data Structures and Algorithms
scanning.
• It is more human-friendly and aligns with the way we typically
calculate expressions.
• It fits better with stack-based architectures (used in compilers and
virtual machines).
• Its evaluation is more straightforward in terms of scanning and
processing operands as they are encountered.
58
Data Structures and Algorithms
59