1 stacks. 2 a stack has the property that the last item placed on the stack will be the first item...

20
1 Stacks

Upload: arthur-griffin

Post on 02-Jan-2016

214 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: 1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,

1

Stacks

Page 2: 1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,

2

Stacks

A stack has the property that the last item placed on the stack will be the first item removed

Commonly referred to as last-in, first-out, or simply LIFO

Page 3: 1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,

3

ADT Stack Operations

1. Create an empty stack2. Determine whether a stack is

empty3. Add a new item to the stack (push)4. Remove from the stack the item

that was added most recently (pop)5. Remove all items from the stack6. Retrieve from the stack the item

that was added most recently

Page 4: 1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,

4

Pseudocode for the ADT Stack Operations

createStack()//Creates an empty stackisEmpty()//Determines whether a stack is emptypush(newItem) throws StackException/*Adds newItem to the top of the stack. Throws

StackException if the insertion is not successful */

pop() throws StackException/*Retrieves and then removes the top of the

stack (the item that was added most recently). Throws StackException if the deletion is not successful */

Page 5: 1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,

5

Pseudocode for the ADT Stack Operations

popAll()//Removes all items from the stackpeek() throws StackException/* Retrieves the top of the stack. That is, peek

retrieves the item that was added most recently. Retrieval does not change the stack. Throws StackException if the retrieval is not successful */

Page 6: 1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,

6

Simple Applications of the ADT Stack - Checking for Balanced

Braces

Curly braces, “{“ and “}” delimits groups of statements

To balance, keep track of each unmatched “{“ and discard one each time you encounter a “}” Push each “{“ encountered onto a stack

and pop one off each time you encounter a “}”

Page 7: 1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,

7

Draft solution - Checking for Balanced Braces

while (not at the end of the string) {if (the next character is a ‘{‘ ) {

stack.push( ‘{‘ )}else if (the character is a ‘}’ ) {

openBrace = stack.pop()} // end if

} //end while

Requirements for balanced braces:

1. Each time you encounter a “}”, it matches an already encountered “{“

2. When you reach the end of the string, you have matched each “{“

Page 8: 1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,

8

Detailed solution – Check a string for Balanced Braces

stack.createStack()bancedSoFar = truei = 0while (balancedSoFar and i < length of aString) { i++//push an open braceif (ch is ‘{‘ ) {

stack.push( ‘{‘ ) }

//close braceelse if ( ch is ‘}’ ) { if (! stack.isEmpty() ) {

openBrace = stack.pop() //pop a matching open brace

} else { //no matching open

bracebalancedSoFar = false

} // end if// ignore all characters other than braces} // end while

Page 9: 1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,

9

Detailed solution – Check a string for Balanced Braces

if ( balancedSoFar and stack.isEmpty() ) {aString has balanced braces

}else {

aString does not have balanced braces} // end if

Input string

{a{b}c}

{

{

{ {

Stack as algorithm executes1 2 3 4

1. push “{“

2. push “{“

3. pop

4. pop

Stack empty balanced

Page 10: 1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,

10

Implementation of the ADT Stack

public interface StackInterface {public boolean isEmpty();

//Determines whether the stack is empty.//Precondition: None.//Postcondition: Returns true if the stack is empty; //otherwise returns false

public void popAll();//Removes all the items from the stack.//Precondition: None//Postcondition: Stack is empty.

public void push(Object newItem) throws StackException;//Adds an item to the top of a stack//Precondition: newItem is the item to be added//Postcondition: If insertion is successful, newItem is

on //the top of the stack.//Exception: Some implementation may throw a

//StackException when newItem cannot be placed on the //stack.

Page 11: 1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,

11

Implementation of the ADT Stack

public object pop() throws StackException;//Removes the top of a stack//Precondition: None//Postcondition: If the stack is not empty, the item that was //added most recently is removed from the stack and returned//Exception: Throws StackException f the stack is emptypublic Object peek() throws StackException; //Retrieves the top of a stack//Precondition: None//Postcondition: If the stack is not empty, the item that was //added most recently is removed from the stack and returned//Exception: Throws StackException if the stack is empty

} //end StackInterface

Page 12: 1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,

12

Class StackException

public class StackException extends java.lang.RuntimeException {public StackException(String s) {

super(s);} // end constructor

} // end StackException

Page 13: 1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,

13

Implementations of the ADT stack that use

(a) an array; (b) a linked list; (c) an ADT list

30

20

10

Array

top 30

20

10

Linked list

top30

20

10

ADT list

top

(a) (b) (c)

Page 14: 1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,

14

An Array-Based Implementation of the ADT Stack

5 13 7 10 …

items

0 1 2 k

k

top

MAX_STACK - 1Array indexes

public class StackArrayBased implements StackInterface {final int MAX_STACK = 50; //maximum size of stackprivate Object items[];private int top;

public StackArrayBased() {items = new Object[MAX_STACK];top = -1;

} // end default constructor

Page 15: 1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,

15

An Array-Based Implementation of the ADT Stack

public boolean isEmpty() {return top < 0;

} // end isEmpty

public boolean isFull() {return top == MAX_STACK – 1;

} // end isFull

public void push(Object newItem) throws StackException {if ( ! isFull()) {

items[++top] = newItem;}else {throw new StackException(“SatckException on push: stack full“);} // end if

} // end push

Page 16: 1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,

16

public void popAll() {items = new Object[MAX_STACK];top = -1;

} // end popAllpublic Object pop() throws StackException {

if (!isEmpty()) {return items[top--];

}else {throws new StackException(“StackException on pop: Stack empty”);} // end if

} // end poppublic Object peek() throws StackException {

if (!isEmpty()) {return items[top];

}else {throws new StackException(“StackException on peek: Stack empty”);} // end if

} // end peek} // end StackArrayBased

Page 17: 1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,

17

Using the ADT stack …

public class StackTest {public static final int MAX_ITEMS = 15;public static void main(String[] args) {

StackArrayBased stack = new StackArrayBased();Integer items[] = new Integer[MAX_ITEMS];for (int i = 0; i < MAX_ITEMS; i++) { items[i] = new Integer(i); if (!stack.isFull()) {

stack.push(items[i]); } // end if} // end for

while (!stack.isEmpty()) {//cast results of pop to IntegerSystem.out.println((Integer)(stack.pop()));

} // end while…

Page 18: 1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,

18

A Reference-Based Implementation of the ADT

Stack

public class StackReferenceBased implements StackInterface {private Node top;public StackReferenceBased() {

top = null;} // end default constructorpublic boolean isEmpty() {

return top == null;} // end isEmptypublic void push(Object newItem) {

top = new Node (newItem, top);} // end pushpublic Object pop() throws StackException {

if (!isEmpty()) {Node temp = top;top = top.getNext();return temp.getItem();

}

Page 19: 1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,

19

A Reference-Based Implementation of the ADT

Stackelse {throw new StackException(“StackException on pop: Stack empty”);} // end if

} // end pop public void popAll() {

top = null; } // end popAll public Object peek() throws StackException {

if (!isEmpty()) {return top.getItem();}

else {throw new StackException(“StackException on peek: Stack empty”);} // end if

} // end peek} // end StackReferenceBased

Page 20: 1 Stacks. 2 A stack has the property that the last item placed on the stack will be the first item removed Commonly referred to as last-in, first-out,

20

Your Turn

Provide implementation of the ADT stack using the ADT list.