• No results found

Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1

N/A
N/A
Protected

Academic year: 2021

Share "Stacks. Stacks (and Queues) Stacks. q Stack: what is it? q ADT. q Applications. q Implementation(s) CSCU9A3 1"

Copied!
15
0
0

Loading.... (view fulltext now)

Full text

(1)

Stacks (and Queues)

1

Stacks

q 

Stack: what is it?

q 

ADT

q 

Applications

q 

Implementation(s)

(2)

3

Stacks and queues

q  A stack is a very important data structure in computing science.

q  A stack is a sequence of elements to which new elements are added (pushed), and from which elements are removed (popped), at the same end.

q  Stack sometimes referred to as a last in, first out structure (LIFO).

q  In a queue, elements are removed from the opposite end to which they are added.

q  Queue sometimes referred to as a first in, first out structure (FIFO).

Stacks and queues

q 

The difference is the remove operation.

add remove add

remove

(3)

Last In First Out

B A

D C B A

C B A

D C B A D E

C B A top top

top

top top A

5

Abstract Data Types (ADTs)

q 

An abstract data type (ADT) is an abstraction of a data structure

q 

An ADT specifies:

n  Data stored

n  Operations on the data

n  Error conditions associated with operations

q 

Example: ADT modeling a simple stock trading system

n  The data stored are buy/sell orders

n  The operations supported are

w order buy(stock, shares, price) w order sell(stock, shares, price) w void cancel(order)

n  Error conditions:

w Buy/sell a nonexistent stock w Cancel a nonexistent order

(4)

The Stack ADT

q  The Stack ADT stores arbitrary objects

q  Insertions and deletions follow the last-in first-out scheme

q  Think of a spring-loaded plate dispenser. (Pez?)

7

The Stack ADT

q  Main stack operations:

n  push(object): inserts an element

n  Object pop(): removes and returns the last inserted element

q  Auxiliary stack operations:

n  Object peek(): returns the last inserted element without removing it. (Sometimes appears as Object top())

n  integer size(): returns the number of elements stored

n  boolean isEmpty(): indicates whether no elements are stored

(5)

9

Stack Operations

Assume a simple stack for integers.

Stack s = new Stack();

s.push(12);

s.push(4);

s.push( s.top() + 2 );

s.pop()

s.push( s.top() );

//what are contents of stack?

Stack usage and limitations

Write an algorithm to Reverse the

contents of an array. How about using a stack?

Write a method to print out contents of

stack in reverse order.

(6)

11

Stack Interface in Java

q 

Java interface corresponding to our Stack ADT

q 

Requires the definition of class EmptyStackException

q 

Different from the built-in Java class java.util.Stack

public interface Stack<E> { public int size();

public boolean isEmpty();

public Object top()

throws EmptyStackException;

public void push(E element);

public Object pop()

throws EmptyStackException;

}

Exceptions

q 

Attempting the execution of an

operation of ADT may sometimes cause an error condition, called an exception

q 

Exceptions are said to be “thrown” by an operation that cannot be executed

q 

In the Stack ADT, operations pop and top cannot be

performed if the stack is empty

q 

Attempting the execution of pop or top on an empty stack throws an

EmptyStackException

(7)

13

Applications of Stacks

q 

Direct applications

n 

Page-visited history in a Web browser

n 

Undo sequence in a text editor

n 

Chain of method calls in the Java Virtual Machine

q 

Indirect applications

n 

Auxiliary data structure for algorithms

n 

Component of other data structures

Method Stack in the JVM

q  The Java Virtual Machine (JVM) keeps track of the chain of active methods with a stack

q  When a method is called, the JVM pushes on the stack a frame containing

n  Local variables and return value

n  Program counter, keeping track of the statement being executed

q  When a method ends, its frame is popped from the stack and control is passed to the method

main() { int i = 5;

foo(i);

} foo(int j) {

int k;

k = j+1;

bar(k);

}

bar(int m) { …

bar PC = 1 m = 6 foo PC = 3 j = 5 k = 6 main PC = 2 i = 5

(8)

Array-based Stack

q 

Allocate an array of some size (pre-defined)

n  Maximum N elements in stack

q 

Bottom stack element stored at element 0

q 

last index in the array is the top

n  What is index when stack is empty?

q 

Increment top when one element is pushed, decrement after pop

15

Array-based Stack

S 0 1 2 t

Algorithm size()

return top + 1 Algorithm pop()

if isEmpty() then

throw EmptyStackException else

top ← top - 1 return S[top + 1]

(9)

17

Array-based Stack (cont.)

q  The array storing the stack elements may become full

q  A push operation will then throw a

FullStackException

n  Limitation of the array- based implementation

n  Not intrinsic to the Stack ADT

S 0 1 2 t

Algorithm push(o) if t = S.length - 1 then throw FullStackException else

t ← t + 1 S[t] ← o

Performance and Limitations

q 

Performance

n  Let n be the number of elements in the stack

n  The space used is O(n)

n  Each operation runs in time O(1)

q 

Limitations

n  The maximum size of the stack must be defined a priori and cannot be changed

n  Trying to push a new element into a full stack causes an implementation-specific exception

(10)

19

Common Stack Error

Stack s = new Stack();

// put stuff in stack

for(int i = 0; i < 7; i++) s.push( i );

// print out contents of stack // while emptying it

for(int i = 0; i < s.size(); i++) System.out.println( s.pop() );

// Output? Why?

Corrected Version

Stack s = new Stack();

// put stuff in stack

for(int i = 0; i < 7; i++) s.push( i );

// print out contents of stack // while emptying it

int limit = s.size();

for(int i = 0; i < limit; i++)

System.out.println( s.pop() );

//or

// while( !s.isEmpty() )

// System.out.println( s.pop() );

(11)

21

Array-based Stack in Java

public class ArrayStack<E>

implements Stack<E> { // holds the stack elements private E S[ ];

// index to top element private int top = -1;

// constructor

public ArrayStack(int capacity) { S = (E[]) new

Object[capacity]);

}

public E pop() throws

EmptyStackException { if isEmpty() {

throw new EmptyStackException (“Empty stack: cannot pop”);

}

E temp = S[top];

// facilitate garbage collection:

S[top] = null;

top = top – 1;

return temp;

}

… (other methods of Stack interface)

Example use in Java

public class Tester { // … other methods

public void intReverse(Integer a[]) { Stack<Integer> s;

s = new ArrayStack<Integer>();

for(int i = 0; i < a.length; a++) s.push(a[i]);

for(int i = 0; i < a.length; a++) a[i] = s.pop();

}

public void floatReverse(Float f[]) { Stack<Float> s;

s = new ArrayStack<Float>();

… (code to reverse array f) … }

(12)

23

Parentheses Matching

q 

Each “(”, “{”, or “[” must be paired with a matching “ ) ” , “ } ” , or “ [ ”

n 

correct: ( )(( )){([( )])}

n 

correct: ((( )(( )){([( )])}

n 

incorrect: )(( )){([( )])}

n 

incorrect: ({[ ])}

n 

incorrect: (

Parentheses Matching Algorithm

Algorithm ParenMatch(X,n):

Input: An array X of n tokens, each of which is either a grouping symbol, a variable, an arithmetic operator, or a number

Output: true if and only if all the grouping symbols in X match Let S be an empty stack

for i=0 to n-1 do

if X[i] is an opening grouping symbol then S.push(X[i])

else if X[i] is a closing grouping symbol then if S.isEmpty() then

return false {nothing to match with}

if S.pop() does not match the type of X[i] then return false {wrong type}

if S.isEmpty() then

return true {every symbol matched}

else return false {some symbols were never matched}

(13)

25

HTML Tag Matching

<body>

<center>

<h1> The Little Boat </h1>

</center>

<p> The storm tossed the little boat like a cheap sneaker in an old washing machine. The three drunken fishermen were used to such treatment, of course, but not the tree salesman, who even as a stowaway now felt that he had overpaid for the voyage. </p>

<ol>

<li> Will the salesman die? </li>

<li> What color is the boat? </li>

<li> And what about Naomi? </li>

</ol>

</body>

The Little Boat

The storm tossed the little boat like a cheap sneaker in an old washing machine. The three drunken fishermen were used to such treatment, of course, but not the tree salesman, who even as a stowaway now felt that he had overpaid for the voyage.

1. Will the salesman die?

2. What color is the boat?

3. And what about Naomi?

For fully-correct HTML, each <name> should pair with a matching </name>

Infix notation

q  Consider the aithmetic expression:

3 + 4 * (5 - 2) - 3 - 1

q  Binary operators requires two operands.

q  To evaluate the expression, we use the following rules:

* and / have higher precedence than + and -,

q  when operators have the same precedence, we apply them from left to right,

q  brackets change the order of precedence.

q  Hence the following example gives a different answer:

3 + 4 * 5 - 2 - (3 - 1)

(14)

27

Reverse Polish

q  With reverse Polish (postfix) notation, no precedence rules or parentheses required!

q  In postfix notation, we put the operator after its operands instead of between them.

q  Hence, instead of 5 + 4, we have 5 4 +.

Postfix Notation

q  The first expression above, would be re-written as:

3 + 4 * (5 - 2) - 3 - 1 3 4 5 2 - * + 3 - 1 –

q  while the second would be written as:

3 + 4 * 5 - 2 - (3 - 1) 3 4 5 * + 2 - 3 1 - -

q  The operands are written in the same order while the operators are now written in the order in which they are to be applied.

(15)

(continued)

29

Examples

q  Let us first apply it to our simple example: 5 4 +

Answer is 9!

Next ‘Token’: 5 4 +

q  With the expression: 3 4 5 2 - * + 3 - 1 - 5

4

5 9

2 5 4 3

3 4 3

12

3 15 3

15 12 1

12 11

References

Related documents

If the wood is already painted, clean the surface, apply an oil-based or latex stain-resistant primer and then top coat.. Before priming and repainting, apply a

q Sores in mouth q Pus in urine q No q Yes If yes, at what age: ____ qLoss of taste q Discharge from penis/vagina Date of last Pap smear: ____________ q Dryness

EmptyQueueException No corresponding built-in Java class (although LinkedList has all the Queue methods). public interface Queue { public

Johns Hopkins Department of Computer Science Course 600.226: Data Structures, Professor: Jonathan Cohen. Queue Interface in Java Queue Interface

public int size(); // return the number of // elements in the stack public boolean isEmpty(); // see if the stack.. //

 Implementation strategies for stacks, queues, and hash tables  Implementation strategies for trees..  Strategies for choosing the right

• 24 Hour Dealing Room 24 Hour Dealing Room service which supports Cantonese, Mandarin and English Cantonese, Mandarin and

4.8 (continued) (f) Enqueuing number 6 to a queue storing 2, 4, and 8; (d–e) the same queue seen as a one-dimensional array with the last element (d) at the end of the array and (e)