0% found this document useful (0 votes)
26 views63 pages

CHP 5 Stack

The document discusses stacks and their implementation and applications. It defines a stack as a type of list where elements can only be inserted or removed from one end, following LIFO order. Stacks can be implemented using linked lists or arrays. The key stack operations are push, pop, peek, and isEmpty. Stacks are widely used in compilers, operating systems, and for arithmetic expressions. Examples show how to implement a Stack class and use basic stack operations. The document also discusses converting infix expressions to prefix and postfix notation using stacks.

Uploaded by

2022842434
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)
26 views63 pages

CHP 5 Stack

The document discusses stacks and their implementation and applications. It defines a stack as a type of list where elements can only be inserted or removed from one end, following LIFO order. Stacks can be implemented using linked lists or arrays. The key stack operations are push, pop, peek, and isEmpty. Stacks are widely used in compilers, operating systems, and for arithmetic expressions. Examples show how to implement a Stack class and use basic stack operations. The document also discusses converting infix expressions to prefix and postfix notation using stacks.

Uploaded by

2022842434
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/ 63

Chapter 5

STACK
FUNDAMENTALS OF DATA STRUCTURES (CSC248)

PREPARED BY:
MISS MAZNIE MANAF
DEFINITION OF STACK

 A type of list
 in which data could be inserted and removed from only
one end of the list known as the top
 has Last In First Out (LIFO) / First in Last Out (FILO)
characteristics
EXAMPLE OF STACK
INTRODUCTION

 Stack can be implemented using linked list or sequential list


 In this course, self-defined Class Stack is using a constrained version of a linked list,
new node can be added and removed to/from a stack only at the top or front of
the list.
 Reference link of the last node in stack is set to null to indicate the bottom of the
stack
 Stack using linked list structure – dynamic data structure where elements are stored
anywhere in memory

Top

node Bottom
THE USES OF STACK (ADVANTAGES)

 Stacks are widely used in Compiler and Operating System


 Stacks are used to generate machine language code for arithmetic
expression, to check pair of parenthesis and curly braces.
 Stacks are also used to solve complex arithmetic problems.
 Stacks support recursive calls of the methods in the same manner as they
do conventional non-recursive method calls (call of method within
method)
BASIC OPERATIONS

 Push – inserts data on top of a stack


 Pop – removes data from the top of a stack
 IsEmpty – checks whether the stack is empty
 Peek – retrieves the data at the top of a stack
BASIC OPERATION: METHODS

 public Object push (Object element)


// returns the element that has been inserted at the top of the stack

 public Object pop ( )


// return the element that has been removed on the top of the stack object

 public Object peek( )


// reference to the top element in a stack object is returned

 public boolean isEmpty( )


// return true if a stack has no elements, otherwise return false
//the creation of stack
Stack s = new Stack( );
OF CLASSES:
STACK,
IMPLEMENTATION LINKEDLIST,
NODE
CLASS STACK DEFINITION

public class Stack extends LinkedList {


public Stack() { }// constructor
public void push(Object elem) { insertAtFront(elem); }
public Object pop( ) { return removeFromFront(); }
public Object peek() { return getFirst(); }
} // end Stack
EXAMPLE 1

public class StackString {


public static void main (String [] args) {
Stack myStack = new Stack ();

myStack.push ("Ahmad");
myStack.push ("Nurul");
System.out.println(myStack.pop());
}
}
EXAMPLE 2

public class StackExample {


public static void main (String [] args) {
Stack myStack = new Stack( );
myStack.push(“6”);
myStack.push(“1”);
myStack.push(“8”);
myStack.push(“5”);
System.out.println (“The top element in the stack is” + myStack.peek( ));
myStack.pop ( );
System.out.println (“Data in the stack : “);
System.out.println (myStack.pop( ));
}
}
EXAMPLE 3

public class StackApp { System.out.println("DATA ON THE TOP : ");


public static void main(String [] args) { System.out.println(theStack.peek());
Stack theStack = new Stack();
System.out.println("DATA IN THE STACK : ");
theStack.push("3"); while (!theStack.isEmpty())
theStack.push("5"); {
for (int i=0; i<3; i++) { System.out.println(theStack.pop());
String num = JOptionPane. showInputDialog("Enter a }
number"); } // main
theStack.push(num); } // StackApp
}
NOTE:

 Operation pop will cause data to be removed from the stack


 To just display the data in the stack, you need to pop and save them in a
temporary stack
 After finished, you need to pop them out from the temporary stack and
push into the first stack.
EXERCISE 1

 Draw the diagrams for the following statements:


push(8);
push(5);
pop();
push(3);
pop();
pop();
push(4);
push(10);
EXERCISE 2

 Determine the value of x and y for the following program segment. Then,
draw the latest diagram:

Stack s=new Stack(); x=s.pop();


y=s.peek();
int x=10, y=5;
s.pop();
s.push(x);
s.push(6);
s.push(y);
s.push(x+y);
EXERCISE 3

BEFORE AFTER
 Write a program which receives one D D
string data, then insert every character
A T
from the string into a stack of type char
named alpha. And then, removes the T S
vowels from the stack. A T
S R
Example: DATASTRUCT T C
R T
U
C
T
EXERCISE 4

 Write a program which stores 6 integer numbers into a stack named


stackOne
 Then copy the positive even numbers from stackOne into another stack
named stackTwo where the order of the data is as the same as in
stackOne. Make sure that stackOne still have all of its elements at the end
of the program.
 Remove all elements except the positive odd numbers from stackOne.
And this time the order of data in the stackOne will be reversed.
INFIX,
APPLICATION PREFIX,
Arithmetic Expression
POSTFIX
APLICATION OF STACKS

 reversing the order of items


 converting infix expressions to prefix or postfix forms (From prefix and
postfix to infix (will be discussed in Expression Tree))
 evaluating postfix expressions
 checking matching brackets in mathematical expressions
 storing data before method / function calls
APLICATION OF STACKS

 Searching – search a particular element in stack (check and get the


elements (using pop method).
 Manipulating – do some operation on Stack
(Example : calculate average,determine maximum & minimum and etc.)
 Important thing about application using stack:
 is that stack must be popped (remove data) in order to traverse the stack
 It is important to keep popped data into temporary stack if the data need to
be used again
 Keep track the order of the data if the order is signed by using temporary stack
MATHEMATICAL EXPRESSIONS

EXPRESSION DISCRIPTION EXAMPLE


INFIX - Operator is placed A+B
between two
operands
- Normal notation
PREFIX - Operator is placed +AB
before operands
- Polish notation
POSTFIX - Operator is placed AB+
after operands
- Reverse Polish
notation
Order of Operator Sequence when
precedence both exist
Highest () Left to Right

$ Right to Left

*, / Left to Right,
whichever comes
first
Lowest +, - Left to right,
whichever comes
first
ARITHMETIC EXPRESSIONS

Prefix Notation Infix Notation Postfix Notation

A+B*C

(A+B) * C

A–B+C

A – (B+C)
CONVERTION

Infix to Prefix (without using stack)


i) Infix: [ A + B] iii) Infix: ( A + B ) * C $ 2
A+B * C$2
Prefix: [+ A B]
[+AB]
[$C2]
ii) Infix: C $ A + B
[* +AB $C2]
C$A + B
Prefix: * + A B $ C 2

[$CA]
[ + [$CA] B]
Prefix: + $ C A B
CONVERTION

Infix to Postfix (without using stack)


i) Infix: [ A + B] iii) Infix: ( A + B ) * C $ 2
A+B * C$2
Postfix: [A B +]
[AB+]
[C2$]
ii) Infix: C $ A + B
[AB+ C2$ *]
C$A + B
Postfix: A B + C 2 $ *

[CA$]
[ [CA$] B +]
Postfix: C A $ B +
Application of Stack 1:
Infix to Postfix

 This application converts the infix notation of a given arithmetic expression


into postfix notation.
 In an infix notation the operator is placed in between the operands : a+b
 In a postfix notation the operator is placed immediately after the operand:
ab+
Infix to Postfix Conversion

 There are 3 rules or algorithm in infix to postfix conversion


 Rules (R) for using Stack to change infix to postfix notation:
 R1
 R2
 R3
Infix to Postfix Conversion (Con’t)

R1: Initially, the operatorStack object is empty.


R2: For each operator in the infix string, loop until the operator has been pushed
onto the operatorStack object:
 if the operatorStack object is empty or the operator has higher precedence than the
operator on the top of the operatorStack object then
 Push the operator onto the operatorStack object.

 else
 Pop the operatorStack object and append that popped operator to the postfix string
Infix to Postfix Conversion (Con’t)

R3: Once the end of the input string is encountered,


 Loop until the operatorStack object is empty
 Pop the operatorStack object and append that popped operator to the postfix string
Example: Infix to Postfix

 Example 1: Infix notation A - B

Infix operatorStack Postfix


A empty A
- - A
B - AB
empty AB-
Example: Infix to Postfix

 Example 2: Infix notation A + B - C

Infix operatorStack Postfix


A empty A
+ + A
B + AB
- - AB+
C - AB+C
empty AB+ C -
Example: Infix to Postfix

 Example 3: Infix notation A + B * C

Infix operatorStack Postfix


A empty A
+ + A
B + AB
* +* AB
C +* ABC
+ ABC *
empty ABC *+
Example: Infix to Postfix

 Example 4
 Convert this infix notation to postfix notation
a+c–r/b*r
Solution
Infix operatorStack Postfix
a empty a
+ + a
c c ac
- - ac +
r - ac + r
/ -/ ac + r
b -/ ac + rb
* -* ac + rb /
r -* ac + rb / r
- ac + rb / r *
empty ac + rb / r * -
Parentheses in Infix notation

 How are parentheses handled when converting an infix notation to postfix


notation?
 When a left parentheses “(“ is found in the infix string, it is immediately pushed
onto the operatorStack object
 But its precedence is defined to be lower than any other binary operator
Parentheses in Infix notation (cont)

 When a right parentheses “)” is found in the infix string, the operator
object is repeatedly popped, and the popped element appended to the
postfix string, until the operator on the top of the operatorStack object is
the left paretheses “(“
 Then the left parentheses “(“ is popped but not appended to the postfix
string and the scan of the infix string is continued.
Parentheses in Infix notation (cont)

 Example 5
 Convert this infix notation to postfix notation
x – (y * a / b – (z + d * e) + c) / f
Solution
Infix operatorStack Postfix
x empty x
- - x
( -( x
y -( xy
* -( * xy
a -( * xya
/ -( / xya *
b -( / xya * b
- -( - xya * b/
( -( -( xya * b/
z -( -( xya * b/z
Solution (cont..)
Infix operatorStack Postfix
+ -( -( + xya * b/z
d -( - ( + xya * b/zd
* -( - ( + * xya * b/zd
e -( - ( + * xya * b/zde
) -( - xya * b/zde *+
+ -( + xya * b/zde *+-
c -( + xya * b/zde *+ -c
) - xya * b/zde *+ -c +
/ -/ xya * b/zde *+ -c +
f -/ xya * b/zde *+ -c + f
- xya * b/zde *+- c + f /
Solution (cont..)
Infix operatorStack Postfix
- xya * b/zde *+- c + f /
empty xya * b/zde *+-c+ f /-
Exercise 5

 Translate the following expressions into postfix notation


Application of Stack 2:
Infix to Prefix Conversion

 It is the reverse process of converting an infix to postfix notation


 The saving of operand and operators is easily done with the help of 2
Stacks:
 operandStack
 operatorStack
 The precedence rules for the operatorStack object are exactly the same
as converting infix to postfix
Infix to Prefix Conversion (cont..)

 Algorithm (infix to prefix)


 When an operand is found in the infix string, the operand is pushed onto the
operandStack object
 When an operator found, it is pushed onto the operatorStack object, if the
stack is empty.
 Otherwise one of the following case applies:
1. If the operator is left parentheses, push it onto the operatorStack object (but the left
parentheses has the lowest precedence)
Infix to Prefix Conversion (cont..)

2. If the operator has a higher precedence than the top operator on the
operatorStack object,
 push the operator onto the operatorStack object

3. If the operator’s precedence is equal to, or lower than the precedence of


the top operator on the operatorStack object,
 pop the operator precedence, opt1, from the operatorStack object and
 pop two operands, opnd1 and opnd2, from the operandStack object.
 Join together opt1, opnd2 and opnd1 and push the result onto the
operandStack object
Infix to Prefix Conversion (cont..)

4. If the operator is a right parentheses treat is as having lower priority than +, -, *, /.


 Case 3 will applied until left parentheses is the top operator on the operatorStack object.
 Then pop that left parentheses.

 This process continues until we reach the end of the infix expression.
Infix to Prefix Conversion (cont..)

 Repeat the following actions from case 3 until the operatorStack object is
empty:
a) Pop opt1 from the operatorStack object
b) Pop opnd1 and opnd2 from the operandStack object
c) Join together opt1, opnd2 and opnd1 and push the result onto the operandStack
object

 When operatorStack is finally empty, the top (and only) operand on


operandStack will be the prefix string corresponding to the original infix
expression
Infix to Prefix Conversion (cont..)

 Example 1:
Convert infix notation to prefix notation
a+b*c
Solution
Infix operandStack operatorStack
a a
+ +
b b
a +
* b *
a +
c c *
b +
a
* bc +
a +
+ a * bc
Infix to Prefix Conversion (cont..)

 Example 2:
Convert infix notation to prefix notation
(a – b) * c
Solution
Infix operandStack operatorStack
( (
a a (
- a -
(
b b -
a (
) - ab (
* - ab *

c c *
- ab
* - abc
Infix to Prefix Conversion (cont..)

 Example 3:
Convert infix notation to prefix notation
a + (c – h) / (b * d)
Solution
Infix operandStack operatorStack
a a
+ a +
( a (
+
c c (
a +
- c -
a (
+
h h -
c (
a +
Solution
Infix operandStack operatorStack
) - ch (
a +
/ - ch /
a +
( - ch (
a /
+
b b (
-ch /
a +
Solution
Infix operandStack operatorStack
* b *
- ch (
a /
+
d d *
b (
- ch /
a +
) *bd (
-ch /
a +
Solution

Infix operandStack operatorStack


/-ch*bd +
a
+ a / - ch *bd
Exercise 6

 Translate the following expressions into prefix notation


 a–b+c*d
 (k + l)/(m-n)
 a – (b + c * d) / e
 a + (c – h) / (b * d)
EVALUATING A POSTFIX EXPRESSION
USING A STACK

 Process each data in postfix expression from left to right until there is no
more data
1. If data is an operand , push to stack
2. If data is an operator ,
 pop data into operand1
 pop data into operand2
 RESULT = operand2 operator operand1
 Push RESULT to stack

 The Last value on the stack is the result of the expression


EXAMPLE 4
EXAMPLE 5
Exercise: infix A+B*C
postfix
if A = 4, B= 2 and C = 1

Contents of stack at each operand or operator:

RESULT Operand2 operator Operand1

ANSWER:
Exercise : infix ( A+B )*( C $ D )
postfix
if A = 4, B= 3, C = 2 and D = 1

Contents of stack at each operand or operator:

RESULT Operand2 operator Operand1

ANSWER:
EXERCISE 7

You might also like