2-lecture 5 - stacks and queues - single

48
1 Stacks Chapter 6, page 249-298

Upload: naveen-shanwad

Post on 08-Apr-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 1/47

1

Stacks

Chapter 6, page 249-298

Page 2: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 2/47

2

2

Outline

What is a Stack?

Stack ADT

Various Stack implementations Applications

Bracket Matching

Postfix Calculation

Page 3: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 3/47

3

3

What is a Stack?

A Stack is a collection of data that is accessed ina last-in-first-out (LIFO) manner.

Two operations: ‘push’ and ‘pop’.

push(o)Pop()

stackstack

Page 4: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 4/474

4

Stacks are useful

Calling a function

Before the call, the state of computation is savedon the stack so that we will know where to

resume Recursion

Matching parentheses.

Evaluating algebraic expressions (a+b-c) Traversing a maze.

Page 5: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 5/475

5

Stack ADTpublic interface StackADT {// A collection of objects managed by the// following methods:

public boolean isEmpty ();// return true if empty

public void push (Object o);// insert object o into stack

public Object pop () throws Underflow;// remove and return topmost item

public Object peek () throws Underflow;

// retrieve topmost item}

public class Underflow extends Exception {public Underflow (String s) { super(s); }

}

Page 6: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 6/476

6

ce

Example of Stack ADT usage

Stack s = new Stack();

s.push (“a”);

s.push (“b”);

s.push (“c”);

d = s.peek ();

s.pop ();

s.push (“e”);

s.pop ();

s d 

a

b

c

Note: To be accurate, it is the references to “a”, “b”,“c”, …, being pushed onto or popped from the stack.

Can “a” be replaced by ‘a’ ?

Page 7: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 7/477

7

Stacks Implemented with Linked Lists

Top of Stack = Front of Linked-List 

Stack LL

list

a 1 a 2  a 3  a 4 

head 

BasicLinkedList 

Page 8: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 8/478

8

A class can be defined in 2 ways:

1. via composition:class A {

B b = new B(...); // A is composed of instance of B ... }

2. via inheritance:

class A extends B { ... } // A is an extension of B

3. Can a class be defined via both methods?

class A extends C {

B b = new B(...); ... }

Defining a class

Page 9: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 9/47

Page 10: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 10/4710

10

Via inheritance

class StackLLE extends BasicLinkedList implements StackADT{public void push (Object o) { addHead (o); }

public Object pop () throws Underflow {Object obj = peek();

deleteHead ();return obj;}

public Object peek () throws Underflow {try {

return getHead();} catch (ListIndexOutOfBoundsException e) {throw new Underflow (“Illegal operation on

empty stack”);}

}}

Page 11: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 11/4711

11

Stack Implemented with Array

Can use Array with a top index pointer as animplementation of stack 

F  G 

0  1 7  8  9 2  3  4  5  6 

A B  C  D  E 

top

Stack Arr 

arr

Page 12: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 12/4712

12

Array implementation of Stack class StackArr implements StackADT {

private Object [] arr;private int top;private int maxSize;private final int INITSIZE = 1000;

public StackArr() {arr = new Object[INITSIZE];top = -1;maxSize = INITSIZE ;

}

public boolean isEmpty () {return (top < 0);

}

Page 13: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 13/47

13

13

public Object pop () throws Underflow {

Object obj = peek();top--;return obj;

}

public Object peek () throws Underflow {if (!isEmpty ()) { return arr[top]; }else throw new Underflow (“Illegal op on

empty stack”);}

public void push (Object obj) {if (top >= maxSize-1) enlargeArr();top++;arr[top]=obj;

}

Page 14: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 14/47

14

14

private void enlargeArr () {// double the max sizeint newSize = 2*maxSize;Object [] x = new Object[newSize];

for (int j = 0; j < maxSize; j++) {x[j] = arr[j];

}maxSize = newSize;arr = x;}}

Enlarge the array

Page 15: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 15/47

15

15

Various stack Implementations

Array based (page 263)

Pointer based (page 265)

list (page 266) StackException (page 262)

Page 16: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 16/47

16

16

Java Stack API

Boolean empty()Tests if this stack is empty.

E peek ()Looks at the object at the top of this stack withoutremoving it from the stack.

E pop()Removes the object at the top of this stack andreturns that object as the value of this function.

E push(E item)Pushes an item onto the top of this stack.

int search(Object o)Returns the 1-based position where an object is onthis stack.

Page 17: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 17/47

17

17

Stacks Applications

Many stack applications:

line editing (see textbook)

function call stack  bracket matching

postfix calculation

infix to postfix conversion

Page 18: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 18/47

18

18

Application: Bracket Matching

Ensures that pairs of brackets are properly matched

An Example: {a,(b+f[4])*3,d+f[5]}

Bad Examples:

(..)..) // too many close brackets

(..(..) // too many open brackets

[..(..]..) // mismatched brackets

Page 19: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 19/47

19

19

Bracket Matching

Create empty stack For every char read

if open bracket thenpush onto stack 

if close bracket, then

pop from the stack if doesn’t match or underflow thenflag error 

if stack is not empty then flag error 

Example{a,(b+f[4])*3,d+f[5]}

Stack

{

(

[

)

}

]

[ ]

Page 20: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 20/47

20

20

Expressions,Operators and operands

+, -, *, /, %

=, ~, !

Expression: a = b + cOperands: a, b, c

Operators: =,+

Page 21: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 21/47

21

21

Infix, Prefix, and Postfix Notations

Infix - operand1 operator operand2Prefix - operator operand1 operand2Postfix - operand1 operand2 operator

(2+3)*4

2+(3*4) 2 3 4 * +

2+3*4

infix2 3 + 4 *

postfix

ambiguous, need () or

precedence rules

Unique interpretation

Page 22: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 22/47

22

22

Postfix Calculation

Computation of arithmetic expressions can beefficiently carried out in Postfix notation with thehelp of a stack:

Create an empty stackFor each item of the expression,

If it is an operand,push it on the stack

If it is an operator,pop arguments from stack;perform the operation ;push the result onto the stack

Page 23: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 23/47

23

23

3147

Evaluating Postfix Expressions

2

4

Stack

Expr

2

3

4

+

*

s.push (2)s.push (3)

s.push (4)

arg2 = s.pop ()

arg1 = s.pop ()

s.push (arg1 + arg2)arg2 = s.pop ()

arg1 = s.pop ()

s.push (arg1 * arg2)

2*(3+4) 2 3 4 + *

arg1

arg2

4

3

7

2

code

Page 24: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 24/47

24

24

The precedence rules can be implementedin a table by assigning an appropriatelevel number to each operator.

This table can be found in many books.• * / have higher precedence over + -

• Operators at the same level: Associate

from left to right.

Precedence Rules

3-

3+

5/

5*

levelno.operator

Page 25: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 25/47

25

25

Converting Infix Expressions toEquivalent Postfix Expressions

for (each character ch in the infix expression) {

switch (ch) {

case operand:

postFixExp = postFixExp + ch; break;

case ‘(‘: stack.push(ch); break;

case ‘)’:

while (top of stack is not ‘(‘)

postFixExp = postFixExp + stack.pop();

stack.pop(); break; // remove ‘(‘

Page 26: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 26/47

26

26

Case operator:

while ( !stack.isEmpty() && top of stack is not ‘(‘ &&

precedence(ch) <= precedence(top of stack) )

postFixExp = postFixExp + stack.pop();

stack.push(ch); break;

} end swtich

} end for

while (!stack.isEmpty())

postFixExp = postFixExp + stack.pop();

Page 27: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 27/47

27

27

Infix to Postfix Conversion

Example: a-(b+c*d)/e

Page 28: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 28/47

28

28

Queues

chapter 7, page 299-334

Page 29: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 29/47

29

29

Outline

What is a Queue? Applications

Queue ADT

Various Queue Implementations

Page 30: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 30/47

30

30

What is a Queue?

A Queue is a collection of data that is accessed ina first-in first-out (FIFO) manner.

enqueue(o)dequeue()

isEmpty()

getFront()

Front Rear

Page 31: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 31/47

31

31

Applications

Many Queue applications:

print queue

simulation

breath-first traversal of trees

checking palindrome

Page 32: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 32/47

32

32

Queue ADT

public interface QueueADT {

// A collection of objects managed by the// following methods:

public void enqueue (Object o);// Insert element o at rear

public Object dequeue () throws Underflow;// Remove and return front element

public Object getFront () throws Underflow;// Returns front element

public boolean isEmpty ();// Returns true if queue has no elements

}public class Underflow extends Exception{ public Underflow (String s) { super(s); }}

// empty() for Stack

Page 33: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 33/47

33

33

front  back 

Sample run

Queue q = new Queue ();

q.enqueue (“a”);

q.enqueue (“b”);

q.enqueue (“c”);

d=q.getFront ();

q.dequeue ();

q.enqueue (“e”);

q.dequeue ();

a b c e

d  a

Page 34: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 34/47

34

34

Recognizing Palindrome

A string which reads the same either left to right , or right to left is known as a palindrome Palindromes : “r a d a r” and “d e e d” 

Counter Example : “d a t a” 

“c1 c2 c3 c4 c5“

top

< c5, c4, c3, c2, c1 >

front 

< c1, c2, c3, c4, c5 >

ProcedureGiven a string, use

a Stack to reverse its ordera Queue to preserve its order

Check if the sequences are the same

Page 35: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 35/47

35

35

Code to check for palindromepublic static boolean palindrome (String v) throws Exception {

Stack s = new Stack ();Queue q = new Queue ();int len = v.length ();

// push string into stack and queuefor (int j=0; j < len; j++) {Character c = new Character (v.charAt (j));s.push (c);q.enqueue (c);

}

// pop, dequeue, and comparewhile (!s.isEmpty()) {Character vs = (Character) s.pop();

Character vq = (Character) q.dequeue();if (!vs.equals(vq)) return false;}return true;

}

Page 36: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 36/47

36

36

Queue Implemented with Linked List

Can use TailedLinkedList as underlying

implementation of QueuesQueue

list

a1 a2 a3 a4

head tail

TailedLinkedList 

addTail

Page 37: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 37/47

37

37

Via Compositionclass QueueLL implements QueueADT {

private TailedLinkedList list; // composition

public QueueLL () { list = new TailedLinkedList(); }

public boolean isEmpty() { return list.isEmpty (); }

public void enqueue (Object o) { list.addTail (o); }

public Object dequeue () throws Underflow {Object obj = getFront();

list.deleteHead ();return obj;}

public Object getFront() throws Underflow {try {

return list.getHead();} catch (ListIndexOutOfBoundsException e) {throw new Underflow (“Illegal operation on

empty queue”);}

Page 38: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 38/47

38

38

Via inheritance

class QueueLLE extends TailedLinkedList implements

QueueADT {

public void enqueue (Object o) { addTail (o); }

public Object dequeue () throws Underflow {Object obj = getFront();

deleteHead ();return obj;}

public Object getFront() throws Underflow {try {

return getHead();} catch (ListIndexOutOfBoundsException e) {throw new Underflow (“Illegal operation

on empty queue”);}

}

}

Page 39: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 39/47

39

39

Array implementation of Queue

Can use an array with front and back pointersto implement a queueQueue

front

back

arr 0 1 7  8 92 3 4 5 6 

A B C  D E F G

Page 40: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 40/47

40

40

Circular Array

Given a queue

01 7  8 92 3 4 5 6 

A B C  D E F G

frontback

front

back

AB

DEF

G

0

1

8

9

2

3

45

it is best to view the arrayas a circular structure:

// To advance the indexes, use

front = (front+1) % maxsize;back = (back+1) % maxsize;

F B

Page 41: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 41/47

41

41

Caution! Ambiguous full/empty state!

What does (F==B) denote?

FB

Queue

EmptyState

c d e

BF

f  Queue

Full

State

size 0 size 4

c d e

B F

Alternative - Leave a Gap!

No need for size field.

Full Case : (((B+1)% maxsize)==F)

Solution 1 – maintain queue size.

Page 42: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 42/47

42

42

Array implementation of Queue

class QueueArr implements QueueADT {

private Object [] arr;private int front,back;private int maxSize;private final int INITSIZE = 1000;

public QueueArr () {arr = new Object[INITSIZE ];front = 0; back=0;maxSize = INITSIZE ;

}public boolean isEmpty () {

return (front == back);}

Page 43: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 43/47

43

43

public Object dequeue () throws Underflow {Object obj = getFront();arr[front] = null; // prevent memory leak!front = (front+1)%maxSize;return obj;

}

public Object getFront() throws Underflow {if (isEmpty())

throw new Underflow (“Invalid operation on empty q”);

elsereturn arr[front];

}

Page 44: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 44/47

44

44

public void enqueue (Object o) {if ((back+1)%maxSize)==front) enlargeArr();arr[back] = o;back = (back+1)%maxSize;}

private void enlargeArr () {int newSize = maxSize * 2;Object [] x = new Object[newSize];for (int j=0; j < maxSize; j++) {

x[j] = arr[ (front+j)%maxSize ];}

front = 0; back = maxSize-1;maxSize = newSize;arr = x;

}} // end class QueueArr

Page 45: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 45/47

45

45

Sample run

Queue q = new

QueueArr();

q.enqueue(“a”);

q.enqueue(“b”);

q.enqueue(“c”);

q.dequeue();

q.dequeue();

q.enqueue(“d”);

q.enqueue(“e”);

q.dequeue();

a

front

Back

b c d e

Page 46: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 46/47

46

46

java.utilInterface Queue<E>

boolean offer(E o)Inserts the specified element into thisqueue, if possible.

E peek ()Retrieves, but does not remove, thehead of this queue, returning null if this queue is empty.

E poll()Retrieves and removes the head of 

this queue, or null if this queue isempty.

enqueue

getFront

dequeue

Page 47: 2-Lecture 5 - Stacks and Queues - single

8/7/2019 2-Lecture 5 - Stacks and Queues - single

http://slidepdf.com/reader/full/2-lecture-5-stacks-and-queues-single 47/47

47

47

java.utilClass LinkedList<E>

int size()Returns the number of elements in this list.

In addition to those defined in Interface Queue ,the above method in the class LinkedList canbe used to implement isEmpty()

Use LinkedList to implement the class Queue!