0% found this document useful (0 votes)
0 views59 pages

Slide 4

The document provides an overview of stacks as a data structure, highlighting their LIFO (Last-In/First-Out) nature and common operations such as push, pop, and top. It discusses stack implementation using arrays and linked lists, along with examples of stack operations and their applications in various scenarios like recursion and expression evaluation. Additionally, it covers error handling with exceptions and specific algorithms related to stack operations.

Uploaded by

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

Slide 4

The document provides an overview of stacks as a data structure, highlighting their LIFO (Last-In/First-Out) nature and common operations such as push, pop, and top. It discusses stack implementation using arrays and linked lists, along with examples of stack operations and their applications in various scenarios like recursion and expression evaluation. Additionally, it covers error handling with exceptions and specific algorithms related to stack operations.

Uploaded by

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

CSC2102: Data Structures and Algorithms

Slide 4

Fall 2024

Syed Muhammad Hassan


Email: [email protected]
1
Data Structures and Algorithms

• 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

▪ Defined structure and operations

⮚ A stack is a data structure of ordered items such that


items can be inserted and removed only at one end.
⮚ Stacks typically used for temporary storage of data.

⮚ A stack is a LIFO (Last-In/First-Out) data structure.


⮚ A stack is sometimes also called a pushdown store. 3
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

⮚ Attempting the execution of an operation of ADT may sometimes cause


an error condition, called an exception.

⮚ Exceptions are said to be “thrown” by an operation that cannot be


executed.

⮚ In the Stack ADT, operations pop and top cannot be performed if the
stack is empty.

⮚ Attempting the execution of pop or top on an empty stack throws an


EmptyStackException.
6
Stack Operations

⮚ Main stack operations:


▪ push(object): inserts an element.
Data Structures and Algorithms

▪ object pop(): removes and returns the last inserted element.

⮚ Auxiliary stack operations:


▪ object top(): returns the last inserted element without removing
it.
▪ integer size(): returns the number of elements stored.
▪ boolean isEmpty(): indicates whether no elements are stored.

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

⮚ The empty operation checks the status of the stack.

⮚ This operation returns true if the stack is empty and false if the stack is
not empty.

11
Example

⮚ A segment of an algorithm that applies the previously defined


operations on a stack S.

12
Selecting storage structures

⮚ Two choices
Data Structures and Algorithms

▪ Select position 0 as top of the stack


▪ Select position 0 as bottom of the stack

13
Select position 0 as top of the stack
Data Structures and Algorithms

⮚ Model with an array


▪ Let position 0 be top of stack

⮚ Problem … consider pushing and popping


▪ Requires much shifting

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

⮚ Thus our design will include


▪ An array to hold the stack elements
▪ An integer to indicate the top of the stack
15
Implementing a Stack

⮚ There are two ways we can implement a stack:


Data Structures and Algorithms

▪ Static implementation (Using an array)


▪ Dynamic implementation (Using a linked list)

16
Implementing a Stack

⮚ Implementing a stack using an array is fairly easy.


Data Structures and Algorithms

▪ The bottom of the stack is at data[0]


▪ The top of the stack is at data[numItems-1]
▪ push onto the stack at data[numItems]
▪ pop off of the stack at data[numItems-1]

17
Implementing a Stack

⮚ Implementing a stack using a linked list isn’t that bad


Data Structures and Algorithms

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

Suppose STACK[SIZE] is a one dimensional array for implementing the


stack, which will hold the data items. TOP is the pointer that points to the
top most element of the stack. Let DATA is the data item to be pushed.

1. If TOP = SIZE – 1, then:


(a) Display “The stack is in overflow condition”
(b) Exit
2. TOP = TOP + 1
3. STACK [TOP] = ITEM
4. Exit
19
Stack (Array Implementation)
⮚ Algorithm for pop:
Data Structures and Algorithms

Suppose STACK[SIZE] is a one dimensional array for implementing the


stack, which will hold the data items. TOP is the pointer that points to the
top most element of the stack. DATA is the popped (or deleted) data item
from the top of the stack.

1. If TOP < 0, then


(a) Display “The Stack is empty”
(b) Exit
2. Else remove the Top most element
3. DATA = STACK[TOP]
4. TOP = TOP – 1
5. Exit 20
Stack Class Implementation
public class Stack {
private int maxSize;
private int[] stackArray;
private int top;

public Stack(int size){


Data Structures and Algorithms

this.maxSize = size;
this.stackArray = new
int[maxSize];
this.top = -1;
}

public long peak(){


return stackArray[top];
}

public boolean isEmpty(){


return (top == -1);
}

public boolean isFull(){


return (maxSize-1 == top);
}
} 21
Push() and Pop()
public void push(int j){
if(isFull()){
System.out.println("Stack is
full !");
}
else{
Data Structures and Algorithms

top++;
stackArray[top] = j;
}
}

public int pop(){


if(isEmpty()){
System.out.println("Stack is
empty!");
return '0';
}
else{
int old_top = top;
top--;
return stackArray[old_top];
}
}
22
PrintStack

public void printStack(){


Data Structures and Algorithms

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

public void push(int value){


Node extraNode = first;
first = new Node();
first.data = value;
first.next = extraNode;
System.out.println(value+" is pushed into
stack.");
}

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;
}

public int peek(){


return first.data;
}

public boolean isEmpty(){


return (first == null);
}

26
PrintStack

public void printStack(){


Data Structures and Algorithms

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;
}
}

public int min(){


if(isEmpty())
throw new IllegalArgumentException("Stack is
Empty!");
else {
int min = first.data;
while (!isEmpty()) {
if (min > first.data)
min = first.data;
pop();
}
return min;
}
}
28
public int product(){
if(isEmpty())
throw new IllegalArgumentException("Stack is
Empty!");
else{
int product = 1;
while (!isEmpty()){
product *= pop();
}
Data Structures and Algorithms

return product;
}
}

public void even(){


if(isEmpty())
throw new IllegalArgumentException("Stack is
Empty!");
else{
System.out.println("Even Numbers List: ");
while (!isEmpty()){
if(first.data %2 == 0)
System.out.print(first.data+" ,");
pop();
}
}
} 29
public float average(){
if(isEmpty())
throw new IllegalArgumentException("Stack is
Empty!");
else{
float average, sum=0,count=0;
while (!isEmpty()){
Data Structures and Algorithms

sum += first.data;
count++;
pop();
}
average = sum/count;
return average;
}
}

public void replaceTop(int data){


System.out.println(first.data + " is replaced with
"+data);
first.data = data;
}
30
Applications of Stacks
⮚ Stack applications can be classified into four broad categories: reversing
data, pairing data, postponing data usage and backtracking steps.
Data Structures and Algorithms

⮚ 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

⮚ Reversing data items requires that a given set of data


Data Structures and Algorithms

items be reordered so that the first and last items are


exchanged, with all of the positions between the first and
last also being relatively exchanged. For example, the list
(2, 4, 7, 1, 6, 8) becomes (8, 6, 1, 7, 4, 2).

32
Pairing data items

⮚ We often need to pair some characters in an expression. For example,


Data Structures and Algorithms

when we write a mathematical expression in a computer language, we


often need to use parentheses to change the precedence of operators.
The following two expressions are evaluated differently because of the
parentheses in the second expression:

⮚ When we type an expression with a lot of parentheses, we often forget to


pair the parentheses. One of the duties of a compiler is to do the
checking for us. The compiler uses a stack to check that all opening
parentheses are paired with a closing parentheses. 33
⮚ Algorithm to check if all opening parentheses are paired with a closing
parenthesis.
Example
Data Structures and Algorithms

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:

1. Prologue: Save the parameters, local variables, and return address.

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

3. Epilogue: Restore the most recently saved parameters, local variables,


and return address. 35
Data Structures and Algorithms

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

⮚ Recursive Solution for the Tower of Hanoi with algorithm


Data Structures and Algorithms

▪ Let’s call the three peg Src(Source), Aux(Auxiliary) and st(Destination).

1) Move the top N – 1 disks from the Source to Auxiliary tower


2) Move the Nth disk from Source to Destination tower
3) Move the N – 1 disks from Auxiliary tower to Destination tower.
Transferring the top N – 1 disks from Source to Auxiliary tower can
again be thought of as a fresh problem and can be solved in the same
manner. So once you master solving Tower of Hanoi with three disks,
you can solve it with any number of disks with the above algorithm.
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

▪ Powers of two help reveal the pattern:


Number of Disks (n) Number of Moves
1 2^1 - 1 = 2 - 1 = 1
2 2^2 - 1 = 4 - 1 = 3
3 2^3 - 1 = 8 - 1 = 7
4 2^4 - 1 = 16 - 1 = 15
5 2^5 - 1 = 32 - 1 = 31
EXPRESSION

⮚ Another application of stack is calculation of postfix expression. There


Data Structures and Algorithms

are basically three types of notation for an expression (mathematical


expression; An expression is defined as the number of operands or data
items combined with several operators.)
1. Infix notation
2. Prefix notation
3. Postfix notation

46
EXPRESSION
⮚ 1. Infix notation
▪ The infix notation is what we come across in our general mathematics,
Data Structures and Algorithms

where the operator is written in-between the operands. For example :


The expression to add two numbers A and B is written in infix notation
as:
A+B
2. Prefix notation
▪ The prefix notation is a notation in which the operator(s) is written
before the operands, it is also called polish notation in the honor of the
polish mathematician Jan Lukasiewicz who developed this notation. The
same expression when written in prefix notation looks like:
+AB
47
EXPRESSION

⮚ 3. Postfix notation
▪ In the postfix notation the operator(s) are written after the operands, so
Data Structures and Algorithms

it is called the postfix notation (post means after), it is also known as


suffix notation or reverse polish notation. The above expression if written
in postfix expression looks like:
AB+

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 + (B C *) Convert the multiplication


A (B C *) + Convert the addition
A B C * + Postfix form
The rules to be remembered during infix to postfix conversion are:
1. Parenthesize the expression starting from left to light.
2. During parenthesizing the expression, the operands associated with operator
having higher precedence are first parenthesized. For example in the above
expression B * C is parenthesized first before A + B.
3. The sub-expression (part of expression), which has been converted into
postfix, is to be treated as single operand.
4. Once the expression is converted to postfix form, remove the parenthesis. 49
Example 1
Give postfix form for A + [ (B + C) + (D + E) * F ] / G
Solution. Evaluation order is
Data Structures and Algorithms

A + { [ (BC +) + (DE +) * F ] / G}

A + { [ (BC +) + (DE + F *] / G}

A + { [ (BC + (DE + F * +] / G} .

A + [ BC + DE + F *+ G / ]

ABC + DE + F * + G / + Postfix Form 50


Example 2
Give postfix form for (A + B) * C / D + E ^ A / B
Solution. Evaluation order is
Data Structures and Algorithms

[(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

3. If an operand is encountered, add it to Q.


4. If a left parenthesis is encountered, push it onto stack.
5. If an operator ⊗ is encountered, then:
(a) Repeatedly pop from stack and add P each operator (on the top of stack),
which has the same precedence as, or higher precedence than ⊗.
(b) Add ⊗ to stack.
6. If a right parenthesis is encountered, then:
(a) Repeatedly pop from stack and add to P (on the top of stack until a left
parenthesis is encountered.
(b) Remove the left parenthesis. [Do not add the left parenthesis to P.]
7. Exit.
52
Example 3
⮚ Infix String : a+b*c-d
▪ Initially the Stack is empty and our Postfix string has no characters. Now, the
first character scanned is 'a'. 'a' is added to the Postfix string. The next character
Data Structures and Algorithms

scanned is '+'. Being an operator, it is pushed to the stack.

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

• 3. Eliminates the Need for Operator Precedence Rules


• 4. Easier Parsing in Compilers
• 5. Useful for Stack-Based Architectures
• 6. Supports Efficient Expression Evaluation in Limited Memory
• 7. Easier to Implement for Complex Expressions

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

way to evaluate expressions. It also provides an unambiguous


representation of expressions like postfix does, but it’s more suited to
scenarios where an expression is processed recursively rather than
iteratively with a stack.

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

Postfix (Reverse Polish


Aspect Prefix (Polish Notation)
Notation)
Use of parentheses Not needed Not needed
Evaluation order Left to right Right to left
Evaluation ease Very easy with a stack Slightly harder with a stack
Human readability Less intuitive Less intuitive
Efficient, widely used in Efficient, but less commonly
Machine processing
compilers used
Expression evaluation, Parsing, certain recursive
Practical use cases
calculators systems

59

You might also like