8
1 CS 101 Data Structures and Algorithms 06 Stacks 06 Stacks CJD Pushdown Stack a linear data st ructure t hat can be accessed only at one of its ends for storing and retrieving data. This end is called the top of the stack. Principle : LIFO (Last-In First-Out) Example: Cafeteria Trays Stacks Stack Juan Kiko Pedro Kulas top CJD Example Stacks CJD Example Stacks

CS101 06 Stacks

Embed Size (px)

Citation preview

Page 1: CS101 06 Stacks

8/7/2019 CS101 06 Stacks

http://slidepdf.com/reader/full/cs101-06-stacks 1/8

1

CS 101Data Structuresand Algorithms

06 Stacks06 Stacks

CJD

Pushdown Stack – a linear data structure thatcan be accessed only at one of its ends for storingand retrieving data. This end is called the top of

the stack.

Principle : LIFO (Last-In First-Out)

Example: Cafeteria Trays

Stacks

Stack

Juan

KikoPedro

Kulastop

CJD

Example Stacks

CJD

Example Stacks

Page 2: CS101 06 Stacks

8/7/2019 CS101 06 Stacks

http://slidepdf.com/reader/full/cs101-06-stacks 2/8

2

CJD

Stack Operations

clear() – clears the stack

isEmpty() – checks if the stack is empty

push(el) – Puts element el on top of the stack

pop() – removes and returns the top element

from the stack.

top() – returns the top element of the stackwithout removing it.

CJD

Common Stack Implementations

1. Array

push = increase index for new top

pop = reduce index for new top

2. Linked List

push = addToHead

pop = deleteFromHead

CJD

Java Implementation IssuesDesired :

• Reusable class definition regardless of underlying type.

• Maintain encapsulation.

Generic Class Limitations :

• Generic classes do not allow creation of generic arrays from within the class

instances of the generic class from within the class

arrays of the generic class from anywhere

Workaround :

• Define separate stack classes per type (drawback : multipledefinitions – not reusable) or

• Use an Object array (drawback : must cast back)

CJD

Stack Array Per Type

public class StackInt {

private int top = 0;

private final static int stackMax = 100;

 // highest index of stk array

private int[] stk = new int[stackMax+1];public StackInt() {

}

 // other methods

}

Elsewhere:  StackInt s = new StackInt();

Page 3: CS101 06 Stacks

8/7/2019 CS101 06 Stacks

http://slidepdf.com/reader/full/cs101-06-stacks 3/8

3

CJD

Java Generic Stack Workaroundpublic class Stack<T> {

private int top = 0;

private final static int stackMax=100;

 // highest index of stk array

private Object[] stk = new Object[stackMax+1];

 //Elements must be cast back.

public Stack() {  // constructor

}

 // other methods

}

CJD

Stack Array Operations (1)

push(s,el)

if s.top = s.stackMax  // is stack full ?

print(“Stack Push Overflow Error”)

else s.top s.top + 1

s.stk[s.top] el

clear(s)  // in Java, s is passed as the implied parameter “this”

s.top 0

isEmpty(s)

if s.top = 0

return true

else

return false

CJD

Stack Array Operations (2)pop(s)

if isEmpty(s)

print(“Stack Pop Underflow Error”);

return null

else

s.top s.top – 1

return (T)s.stk[s.top + 1]  // cast back if generic

top(s)

if isEmpty(s)

print(“Stack is Empty”)

return null

else

return (T)s.stk[s.top]  // cast back if genericCJD

Error Handling in Java

 // incomplete code

try

{

Stack<Integer> st = new Stack<Integer>();

st.clear();

Integer x = st.pop();  // pop should throw error

}

catch (Exception e)

{

System.out.println(“Stack Pop Underflow Error”);

}

Page 4: CS101 06 Stacks

8/7/2019 CS101 06 Stacks

http://slidepdf.com/reader/full/cs101-06-stacks 4/84

CJD

Example: A * * B C D * - E * Fstack<Character> st = … // create instance of stack

clear(st)

push(st,‘A’) // st = A (top)

pop(st) // st =

pop(st) // Stack Pop Underflow Error

push(st,‘B’) // st = B (top)

push(st,‘C’) // st = B C (top)

push(st,‘D’) // st = B C D (top)

pop(st) // st = B C (top)print(top(st)) // C st = B C (top)

push(st,‘E’) // st = B C E (top)

print(pop(st)) // E st = B C (top)

push(st,‘F’) // st = B C F (top)CJD

Linear SLL Stack Implementation

clear() – code: head = tail = null; // tail not needed

isEmpty() – public boolean isEmpty()

push(el) – public void addToHead(T el)

pop() – public T deleteFromHead()

top() – code : return head.info;

CJD

Some Applications of Stacks

• String Reversal

• Parenthesis Matching – homework or lab work!

• Expression Notation Conversion

• Expression Evaluation

• Memory Management

• Method Calls / Backtracking

CJD

Expression Notations

Let X = A ◊◊◊◊ B, where ◊◊◊◊ is a binary operator +, -, ×, / 

Infix Notation : operator between operands

A ◊◊◊◊ B

This often results in ambiguity; It requires precedence ofoperators and parentheses for d isambiguation.

Prefix Notation : operator before operands

◊◊◊◊ A B

Postfix Notation : operator after operands

A B ◊◊◊◊

Page 5: CS101 06 Stacks

8/7/2019 CS101 06 Stacks

http://slidepdf.com/reader/full/cs101-06-stacks 5/85

CJD

Notation Conversion

Determine the prefix and postfix notations forA + B / C – D * E

ABC/+DE*--+A/BC*DE(A+B/C) and (D*E)-

A B C / ++ A / B CA and (B/C)+

D E ** D ED and E*

B C /  / B CB and C/

PostfixPrefixOperandsOrder

CJD

Precedence of Operations

Highest – Evaluated first

1. Parenthesis – left to right

2. Multiplication and Division – left to right

3. Addition and Subtraction – left to right

Lowest – Evaluated last

Assuming there are no other operators.

A + B / C – D * E

3rd 1st 4th 2nd

1st is highest; 4th is lowest

CJD

Infix to PostfixLet X[1..n] contain the n items (operands and operators of avalid non-empty expression) in infix notation.

Let S be an empty stack

for i 1 to n

if X[i] is an operand, print(X[i])

else,  // X[i] is an operator

while ( not isEmpty(S) and

X[i] has lower precedence than top(S) )

print(pop(S))

push(S, X[i] )  // only operators are in stack

while not isEmpty(S)

print(pop(S))  // pop all remaining operators

Example: Infix = A + B / C – D * E Postfix = A B C / + D E * -CJD

Infix to PrefixLet X[1..n] contain the n items (operands and operators of a

valid non-empty expression) in infix notation.

Let optr, rev be two empty stacks

for i n downto 1

if X[i] is an operand, push(rev, X[i] )  // reversed prefix

else,  // X[i] is an operatorwhile ( not isEmpty(optr) and

X[i] has lower precedence than top(optr) )

push(rev,pop(optr)) // reversed prefix

push(optr, X[i] )  // only operators are in optr

while (not isEmpty(optr)) push(rev,pop(optr)) // transfer oprtrs

while (not isEmpty(rev)) print(pop(rev))  // prefix is reversed rev

Example: Infix = A + B / C – D * E Prefix = - + A / B C * D E

Page 6: CS101 06 Stacks

8/7/2019 CS101 06 Stacks

http://slidepdf.com/reader/full/cs101-06-stacks 6/86

CJD

Let X[1..n] contain the n items (operands and operators of a

valid non-empty expression) in postfix notation.

Let S be an empty stack

for i 1 to n

if X[i] is an operand, push(S,X[i])

else, B = pop(S)

A = pop(S)

push(S,evaluate(A X[i] B))

print(“The value of expression is ”, pop(S))

Postfix Evaluation

Example : 7 9 3 / + 2 4 * -

397

37

810

10

4210

2

CJD

Let X[1..n] contain the n items (operands and operators of a

valid non-empty expression) in postfix notation.

Let S be an empty stack

for i 1 to n

if X[i] is an operand, push(S,X[i])

else, B = pop(S)

A = pop(S)

push(S, A X[i] B) //concat

print(“The value of expression is ”, pop(S))

Postfix to Infix with Parentheses

Example : 7 9 3 / + 2 4 * -

397

(9/3)7

(2*4)(7+(9/3))

(7+(9/3))

42(7+(9/3))

((7+(9/3))-(2*4))

CJD

Prefix Evaluation

Let X[1..n] contain the n items (operands and operators of a

valid non-empty expression) in prefix notation.

Let S be an empty stack

for i n downto 1

if X[i] is an operand, push(S,X[i])else, A = pop(S)

B = pop(S)

push(S,evaluate(A X[i] B))

print(“The value of expression is ”, pop(S))

Example : - + 7 / 9 3 * 2 4

24

8

738

938

38

108

2

CJD

Prefix to Infix with Parentheses

Let X[1..n] contain the n items (operands and operators of a

valid non-empty expression) in prefix notation.

Let S be an empty stack

for i n downto 1

if X[i] is an operand, push(S,X[i])else, A = pop(S)

B = pop(S)

push(S, A X[i] B) //concat

print(“The value of expression is ”, pop(S))

Example : - + 7 / 9 3 * 2 4

24

(2*4)

7(9/3)(2*4)

93(2*4)

(9/3)(2*4)

(7+(9/3))(2*4)

((7+(9/3))-(2*4))

Page 7: CS101 06 Stacks

8/7/2019 CS101 06 Stacks

http://slidepdf.com/reader/full/cs101-06-stacks 7/87

CJD

Lists : no objects, no pointers ?

• What if objects and pointers are not available in a

programming language to build linked lists ?

• What if the use of objects and pointers is prohibited ?

Use multi-dimensional arrays for objects & pointers.

For objects, we can use “structs” if available.

87654321Array

0273nextgdo2Data2

OAS1Data1

head=4

How can you efficiently manage the free array elements ?

CJD

Memory Management

Linked list memory management using arrays :

Manage free indices in a stack : top=3,6,5,8,1

Pop elements from stack when a new node is created.

Push elements into the stack when a node is disposed.

This method is similar to how many systems managetheir available main memory and secondary memory

space.

CJD

Method Calls

In runtime environments for programming languages,

procedures, functions or methods are called to performtasks.

After execution, these procedures return to the callingstatement.

As each procedure is called, the state (vars, current line,etc.) of the calling procedure must be memorized.

The called procedure may itself call 0 or moreprocedures.

Those procedures may call more procedures, and soon, and so on.

A stack is used to memorize the states of the calling

procedures that are pending to be completed.

Java’s printStackTrace shows such a stack. CJD

A Recursive Algorithmpublic class TestRecursive {

public TestRecursive() {  //keyboard stream

buffIn = new BufferedReader(new

InputStreamReader(System.in)); }

public void readWrite () {

int cint = 0;if ((cint = buffIn.read()) != '\n') { // omitted throw-catch

readWrite();

System.out.print((char)cint); } }

public static void main(String[] args) {

TestRecursive tr = new TestRecursive();

tr.readWrite(); }

private BufferedReader buffIn;

}

Page 8: CS101 06 Stacks

8/7/2019 CS101 06 Stacks

http://slidepdf.com/reader/full/cs101-06-stacks 8/88

CJD

A Recursive Method

What is this method doing ?Suppose main() calls recursiveA, and you input “UST”,

what is the output ?

public void readWrite () {int cint = 0;

if ((cint = buffIn.read()) != '\n') { // omitted throw-catch

readWrite();

System.out.print((char)cint);

}

}

CJD

Input Reversing Algorithm

Input : UST Output : STU

How does this work internally?

public void reverseR () {int cint = 0;

if ((cint = buffIn.read()) != '\n') { // omitted throw-catch

reverseR();

System.out.print((char)cint);

}

}

CJD

Recursion and Stacks

(to main)

‘U’

line 3

‘S’

(to main)

‘U’

Recursion is implemented by the o/s using stacks.

Input : UST

Output : TSU

Top

Top

(to main)

‘U’

line 3

‘S’

line 3

‘T’

Top

(to main)

‘U’

line 3

‘S’

line 3

‘T’

line 3

' \n'

Top

public void reverseR () {

1 int cint = 0;

2 if ((cint = buffIn.read()) != '\n') {

3 reverseR();4 System.out.print((char)cint);

}

}

CJD

End