You are on page 1of 31

Data Structures and

Algorithm
Stacks
Topics

Working of Stack Data


Stacks Stack Operations
Structure

Example of Stack
Applications
Applications of Stack Data • Reversing a Word
Stack Representation • Evaluation of Arithmetic
Structure expressions
• Infix Notation
• Postfix Notation
Stacks

A linear data structure in which all the insertion


and deletion of data values are done at one end
only.
 Follows a Last-In-First-Out (LIFO) structure –
the last object inserted in the list will be the
first one to be retrieved

Stack Representation Similar to a Pile of Plate


LIFO Principle of Stack

In programming terms, putting


an item on top of the stack is
called “push” and removing an
item is called “Pop”

Stack Push and Pop Operations


Stack Operations

A stack is an object or more specifically an abstract


data structure(ADT) that allows the following
operations:
 Push – adds item at the top
 Pop – removes element from the top
 IsEmpty – check if the stack is empty
 IsFull - check if the stack is full
 Peek – accesses value at the top
Working of Stack Data Structure
A pointer
called TOP is
used to keep
track of the
top element
in the stack.

On popping an
element, we
return the
element
pointed to by
TOP and
reduce its
value.
Stack Representation

 One-dimensional array

0
Stack Representation

 Doubly Linked List


Stack Implementations in Java
// Stack implementation in Java // Remove element from stack
public int pop() {
class Stack { if (isEmpty()) {
private int[] arr; System.out.println("STACK EMPTY");
private int top; System.exit(1);
private int capacity; }
return arr[top--];
// Creating a stack }
Stack(int size) {
arr = new int[size]; // Utility function to return the size of the stack
capacity = size; public int size() {
top = -1; return top + 1;
} }

// Add elements into stack // Check if the stack is empty


public void push(int x) { public Boolean isEmpty() {
if (isFull()) { return top == -1;
System.out.println("OverFlow\nProgram Terminated\n"); }
System.exit(1);
} // Check if the stack is full
public Boolean isFull() {
System.out.println("Inserting " + x); return top == capacity - 1;
arr[++top] = x; }
}
Stack Implementations in Java
public void printStack() {
for (int i = 0; i <= top; i++) {
System.out.println(arr[i]);
}
}

public static void main(String[] args) {


Stack stack = new Stack(5);

stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);

stack.pop();
System.out.println("\nAfter popping out");

stack.printStack();

}
}
Although stack is a simple data structure to
implement, it is very powerful. The most common
uses of a stack are:
❖ To reverse a word - Put all the letters in a stack
and pop them out. Because of the LIFO order of
stack, you will get the letters in reverse order.
Applications of ❖ In compilers - Compilers use the stack to calculate
Stack Data the value of expressions like 2 + 4 / 5 * (7 - 9) by
converting the expression to prefix or postfix
Structure form.
❖ In browsers - The back button in a browser saves
all the URLs you have visited previously in a stack.
Each time you visit a new page, it is added on top
of the stack. When you press the back button, the
current URL is removed from the stack and the
previous URL is accessed.
 Reversing a word is a typical example of
recursion, but it uses stack to temporarily
store an element
 Extracting characters one-by-one from the
input string and pushed onto the stack
Stack Example:
 Popped off the stack and displayed Reversing a
Word
 Stack reverses the order of the characters
because of its last-in-first-out characteristics
Stack Example: Reversing a Word
Evaluation of Expressions

 An expression is made up of operands and operators


A/B*C+D*E
 The operations to be performed on the operands are
described by the associated operator
 Operators of a higher precedence are processed first
 Evaluation is performed from left-to-right
Evaluation of Expressions
 Infix notation - The operator is in-between every pair of
operands.
Format : operand operator operand A+ B

 Postfix notation - The operator is after every pair of


operands.
Format : operand operand operator AB+

 Prefix notation - the operator is before every pair of


operands
Format : operator operand operand +AB
Evaluation of Expressions

 infix expression may be directly translated into postfix


form by beginning with the conversion of the
subexpression with the highest precedence

A+B → AB+
A+B+C → AB+C+
A+B*C → ABC*+
Evaluation of Expressions: Infix to Postfix
(( A / B ) / C) * (D + E) -→
AB/
AB/C/
1 2 4 3 AB/C/DE+
AB/C/DE+*

( A + B ) / (C – A ) + D * E -→
AB+
AB+CA-
1 3 2 5 4
AB+CA-/
AB+CA-/DE*
AB+CA-/DE*+
Exercise

Convert the following infix notation to postfix


notation

1. (A*B+C)/D-E*F
2. P/O+D-S*R
3. J*Q+S-V/B-N
4. H-(A+K)+E*D
5. L/(F-R)+(O*R-(W/D))
Postfix Notation

 The algorithm for Postfix performs the


following operations on expressions written
in infix notation:
▪ Detects errors in the syntax of the infix
expression.
▪ Transforms the infix expression into postfix
notation.
 The algorithm is based on the following
assumptions:
1. Each operand is denoted as a single alphabetic
character.
Postfix 2. The expression may only begin with an operand
or an open parenthesis.
Notation 3. Operands may only be preceded by an operator
or an open parenthesis.
4. Operators may only be preceded by an operand
or a close parenthesis.
5. An open parenthesis may only be preceded by an
operator or another open parenthesis.
 The algorithm is based on the following
assumptions: cont…
6. A close parenthesis may only be preceded by an
operand or another close parenthesis.
Postfix 7. The expression may only end with an operand or
Notation a close parenthesis.
8. All open parentheses must have matching close
parentheses.
9. The expression may have a maximum of 15
operators and operands.
Postfix Notation
 Converting Infix to Postfix
The Algorithm would be:
1. Scan the infix expression from left to right.
2. If the scanned character is an operand, output it.
3. Else,
…..3.1 If the precedence of the scanned operator is greater than the
precedence of the operator in the stack(or the stack is empty or the
stack contains a ‘(‘ ), push it.
…..3.2 Else, Pop all the operators from the stack which are greater than or
equal to in precedence than that of the scanned operator. After doing
that Push the scanned operator to the stack. (If you encounter
parenthesis while popping then stop there and push the scanned
operator in the stack.)
Postfix Notation

 Converting Infix to Postfix


The Algorithm would be: (cont…)
4. If the scanned character is ‘(‘, push it to the stack.

5. If the scanned character is ‘)’, pop the stack and output it until ‘(‘ is
encountered, and discard both the parenthesis.

6. Repeat steps 2-6 until infix expression is scanned.

7. Print the output

8. Pop and output from the stack until it is not empty.


Postfix Notation

 Converting Postfix to Infix


The Algorithm would be:
 If recognize an operand, push it on the stack.
 If recognize an operator, pop its operands, apply the operator and push the
value on the stack.
 Upon conclusion, the value of the infix expression is on the top of the
stack.
Postfix to Infix Notation
ABCD*+/E*F–
Exercise

Convert the following postfix notation to infix


notation
1.AB*C+DEF*-/
2.PO/D+SR*-
3.JQ*S+VB/-N-
4.HAK+-ED*-
5.LFR-/OR*WD/-+
How about infix and postfix notation using algebraic
expression?
Example using algebraic expressions to come up with
an integer value.

Infix Notation
2 + 3 * 4 -1 = 2 + 12 – 1
= 14 – 1
= 13

(4 + 5) * 6 = 9 * 6
= 54
How about infix and postfix notation using algebraic
expression?
Example using algebraic expressions to come up
with an integer value.

Postfix Notation
2 3 4 * + 1 - = 2(12) + 1 -
= (14)1 –
= 13

45+6*= 9*6
= 54
Evaluation of Expressions: Infix to Prefix
(( A / B ) / C) * (D + E) →
/AB
//ABC
1 2 4 3 //ABC+DE
*//ABC+DE

( A + B ) / (C – A ) + D * E →
+AB
+AB-CA
1 3 2 5 4
/+AB-CA
/+AB-CA*DE
+/+AB-CA*DE
Prefix Notation
 Converting Infix to Prefix
The Algorithm would be:
1. Reverse the infix expression i.e A+B*C will become C*B+A.
Note while reversing each ‘(‘ will become ‘)’ and each ‘)’
becomes ‘(‘.
2. Obtain the postfix expression of the modified expression
i.e CB*A+.
3. Reverse the postfix expression. Hence in the example prefix
is +A*BC.
Exercise
Convert the following infix notation to prefix notation

1. (A*B+C)/D-E*F
2. P/O+D-S*R
3. J*Q+S-V/B-N
4. H-(A+K)+E*D
5. L/(F-R)+(O*R-(W/D))

You might also like