Top Banner
Fall 2007 CS 225 1 Stacks Chapter 5
35

Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Dec 20, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 1

Stacks

Chapter 5

Page 2: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 2

Chapter Objectives• To learn about the stack data type and how to

use its four methods: push, pop, peek, and empty

• To understand how Java implements a stack• To learn how to implement a stack using an

underlying array or a linked list• To see how to use a stack in several

applications

Page 3: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 3

Stack Abstract Data Type• A stack is a data structure with the

property that only the top element of the stack is accessible

• The stack’s storage policy is Last-In, First-Out

• A stack can be compared to a Pez dispenser– Only the top item can be accessed– Can only extract one item at a time

Page 4: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 4

Stack Abstract Data Type

• Only the top element of a stack is visible, therefore the number of operations performed by a stack are few– Inspect (peek) the top element– Retrieve (pop) the top element– Push a new element on the stack– Test for an empty stack

Page 5: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 5

Stack ADT Operations

Puts the item on the top of the stack and returns a reference to it.

E push( E obj)

Removes and returns the object at the top of the stack.

E pop()

Returns the object at the top of the stack without removing it.

E peek()

Returns true if the stack is empty and false otherwise.

boolean empty()

BehaviorMethods

Page 6: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 6

Stack Applications

• Stacks are used for– method calls while a program is running

• Two Example programs using stacks– Palindrome finder– Parentheses matcher

Page 7: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 7

Palindrome Finder

• A palindrome is a string that reads the same in either direction– "kayak"– “Able was I ere I saw Elba” – “Madam I'm Adam”

Page 8: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 8

PalindromeFinder Fields

The stack which stores the characters from the string

private

Stack<Character> charStack

The string to be checkedprivate

String inputString

PurposeData Field

Page 9: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 9

PalindromeFinder Methods

Returns true if the original and reverse strings have the same characters (ignoring case)

public boolean isPalindrome

Returns the reverse stringprivate String buildReverse()

Fill the stack with characters from the string

private void fillStack()

Initialize a PalindromeFinderpublic PalindromeFinder( String str)

BehaviorMethod

Page 10: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 10

Parentheses Matching• When analyzing arithmetic expressions, it is

important to determine whether an expression is balanced with respect to parentheses– (a+b*(c/(d-e)))+(d/e)

• Problem is further complicated if braces or brackets are used in conjunction with parenthesis – Parsing a Java program for example

• Solution is to use stacks!

Page 11: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 11

ParenChecker Methods

Returns true if ch is a closed parenthesis.

private static boolean isClose( char ch)

Returns true if ch is an open parenthesis.

private static boolean isOpen( char ch)

Returns true if the expression is balanced with respect to parentheses.

public static boolean isBalanced( String expr)

BehaviorMethod

Page 12: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 12

Algorithm for isBalanced• Create an empty stack of Characters• Set balanced to true.• Set index to 0.• while balanced is true and index< length• Get the next character• if character is '('• push character onto stack• else if character is ')'• pop the top character from the stack• if stack was empty • set balanced to false• return true if balanced is true and stack is empty

Page 13: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 13

Implementing a Stack

• Extending Vector (java.util.Stack)

• Adapting a List

• Using an array

• Creating a linked structure

Page 14: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 14

Stack as an Extension of Vector

• The Java API includes a Stack class as part of the package java.util

• The vector class implements a growable array of objects

• Elements of a vector can be accessed using an integer index and the size can grow or shrink as needed to accommodate the adding and removing of elements

Page 15: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 15

Stack Extends Vector

public class Stack<E>

extends Vector<E>• Stack inherits all the methods and data

of Vector• methods like get( int index) are not

appropriate for a Stack

Page 16: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 16

Stack with a List Component• Can use either the ArrayList, Vector, or

the LinkedList classes as all implement the List interface

• Name of class illustrated in text is ListStack<E>– ListStack is an adapter class as it adapts

the methods available in another class to the interface its clients expect by giving different names to essentially the same operations

Page 17: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 17

Implementing a Stack Using an Array

• Need to allocate storage for an array with an initial default capacity when creating a new stack object

• Need to keep track of the top of the stack

• No size method

• See ArrayStack.java

Page 18: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 18

ArrayStack

Page 19: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 19

Linked Data Structure for Stack• We can implement a stack using a

linked list of nodes

• see LinkedStack.java

Page 20: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 20

Comparing Stack Implementations• Extending a Vector (as is done by Java) is a

poor choice for stack implementation as all Vector methods are accessible

• Easiest implementation would be to use an ArrayList component for storing data

• All insertions and deletions are constant time regardless of the type of implementation discussed– All insertions and deletions occur at one end

Page 21: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 21

Expressions and Stacks• Consider two case studies that relate to

evaluating arithmetic expressions– Postfix and infix notation

• Expressions normally written in infix form– Binary operators inserted between their operands

• A computer normally scans an expression string in the order that it is input; easier to evaluate an expression in postfix form

Page 22: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 22

Expressions

Page 23: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 23

Postfix expressions

• Advantage of postfix form is that there is no need to group subexpressions in parentheses

• No need to consider operator precedence

Page 24: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 24

PostfixEvaluator

Returns true if ch is an operator

private boolean isOperator( char ch)

Pops two operands, applies the operator and returns the result.

private int evalOp( char op)

Returns the value of the expression

public int eval( String expr)

Stack of operandsStack<Integer> operandStack

Attribute/BehaviorField or method

Page 25: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 25

Evaluating Postfix Expressions

Page 26: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 26

Postfix Evaluation Algorithm• Create an empty stack of Integers• while there are more tokens• get the next token• if the first character is a digit• push the integer onto the stack• else• pop right operand• pop left operand• evaluate the operation• push result onto stack• Pop the result and return

Page 27: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 27

Infix to Postfix Conversion

The postfix expressionprivate stringBuilder postfix

Stack of operatorsprivate Stack<Character> operatorStack

AttributeData Field

Page 28: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 28

Infix to Postfix Conversion

Returns true if ch is an operator

private boolean isOperator( char ch)

Returns the precedence of op

private int precedence( char op)

Updates the operator stackprivate void processOperator( char op)

Returns postfix string equivalent it infix

public String convert (String infix)

BehaviorMethod

Page 29: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 29

Infix to Postfix Conversion

Page 30: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 30

Infix to Postfix Conversion

Page 31: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 31

Conversion AlgorithmInitialize postfix to empty StringBuilder

create empty operator stack

while there are tokens in infix string

get the next token

if token is operand

append to postfix

else if token is operator

call processOperator

else

indicate syntax error

pop remaining operators and append to postfix

Page 32: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 32

Algorithm for ProcessOperatorif operator stack is empty push operator onto stackelse topOp -> peek operator stack if current operator has higher precedence push current operator onto stack else while stack not empty and precedence <= current precedence pop top operator and append to postfix if operator stack not empty topOp -> peek operator stack push current operator on the stack

Page 33: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 33

Chapter Review• A stack is a last-in, first-out (LIFO) data

structure• A stack is a simple but powerful data

structure; its four operations include empty, peek, pop, and push

• Stacks are useful to process information in the reverse of the order that it is encountered

• Java.util.Stack is implemented as an extension of the Vector class

Page 34: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 34

Chapter Review (continued)

• Three ways to implement a stack: – Using an object of a class that implements

the List interface as a container– Using an array as a container– Using a linked list as a container

• Stacks can be applied in programs for evaluating arithmetic expressions

Page 35: Fall 2007CS 2251 Stacks Chapter 5. Fall 2007CS 2252 Chapter Objectives To learn about the stack data type and how to use its four methods: push, pop,

Fall 2007 CS 225 35

ProcessOperator with Parensif operator stack is empty or current operator = '(' push operator onto stackelse topOp -> peek operator stack if current operator has higher precedence push current operator onto stack else while stack not empty and precedence <= precedence(topOp) pop top operator if topOp = ')' break append to postfix if operator stack not empty topOp -> peek operator stack if current operator != ')' push current operator on the stack