30
1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

  • View
    219

  • Download
    1

Embed Size (px)

Citation preview

Page 1: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

1

TCSS 342, Winter 2005Lecture Notes

Stacks and Queues

Weiss Ch. 6, pp. 205-209Weiss Ch. 16, pp. 513-537

Page 2: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

2

Review: List method runtimes

Operationadd to start of listadd to end of listadd at given indexcleargetfind index of an objectremove first elementremove last elementremove at given indexsetsizetoString

Array list O(n) O(1) O(n) O(1) O(1) O(n) O(n) O(1) O(n) O(1) O(1) O(n)

Linked list O(1) O(1) O(n) O(1) O(n) O(n) O(1) O(1) O(n) O(n) O(1) O(n)

Page 3: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

3

What operations should we use?

neither list is fast for adding or removing from arbitrary indexes linked list can add/remove from either end

quickly

linked list is bad at getting / setting element values at arbitrary indexes

neither list is fast for searching(indexOf, contains)

Page 4: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

4

How do we use lists? in many cases, we want to use a list, but we

only want a limited subset of its operations example: Use a list to store a waiting line of

customers for a bookstore. As each customer arrives, place him/her at the end of the line. Serve customers in the order that they arrived.

Which list methods do we need here, and which do we not need?

Page 5: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

5

Common idiom: "FIFO" many times, we will use a list in a way

where we always add to the end, and always remove from the front (like the previous example)

the first element put into the list will be the first element we take out of the list First-In, First-Out ("FIFO")

therefore, let's create a new type of collection which is a limited version of List, tailored to this type of usage: a Queue

Page 6: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

6

Abstract data type: Queue queue: a more restricted List with the following

constraints: elements are stored by order of insertion from front

to back items can only be added to the back of the queue only the front element can be accessed or removed

goal: every operation on a queue should be O(1)

Page 7: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

7

Operations on a queue

enqueue: add an element to the back dequeue: remove and return the

element at the front peek: return (but not remove) front

element dequeue or peek on an empty queue causes

an exception

other operations:isEmpty, size

Page 8: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

8

Queue features ORDERING: maintains order elements were

added(new elements are added to the end by default)

DUPLICATES: yes (allowed) OPERATIONS: add element to end of list

(enqueue), remove element from beginning of list (dequeue), examine element at beginning of list (peek), clear all elements, is empty, get size all of these operations are efficient! O(1)

Page 9: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

9

Our Queue interface

public interface Queue {

public void enqueue(Object o);

public Object dequeue();

public Object peek();

public boolean isEmpty();

public int size();

}

Java has no actual Queue interface or class (until v1.5), so we must write our own or simulate it using a normal list we'll assume instructor-provided LinkedQueue

Page 10: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

10

Queue programming example

Queue q = new LinkedQueue();while (!list.isEmpty()) q.enqueue(list.removeFirst());

while (!q.isEmpty()) { Object element = q.dequeue(); list.add(element); list.add(element);}

double the contents of a Linked List (named list), using a LinkedQueue as an auxiliary data structure

e.g. ["hi", "abc", "bye"] --> ["hi", "hi", "abc", "abc", "bye", "bye"] ... in O(n)

Page 11: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

11

Queue programming example

int size = queue.size();for (int i = 0; i < size; i++) { Object element = queue.dequeue(); queue.enqueue(element); queue.enqueue(element);}

double the contents of a Queue (named queue), using no auxiliary data structures

e.g. ["hi", "abc", "bye"] --> ["hi", "hi", "abc", "abc", "bye", "bye"] ... in O(n)

Page 12: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

12

More queue programming The Sieve of Eratosthenes is an algorithm

for finding prime numbers up to some max n store all numbers in [2, n] in a queue

numbers: [2, 3, 4, ..., 23, 24, 25]

now process the queue, removing the first element each time (it will be prime) and eliminating all the remaining numbers that it divides evenly

numbers: [3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25] primes: [2]

numbers: [5, 7, 11, 13, 17, 19, 23, 25] primes: [2, 3]

Page 13: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

13

More queue programming numbers: [7, 11, 13, 17, 19, 23] primes: [2, 3, 5]

numbers: [11, 13, 17, 19, 23] primes: [2, 3, 5, 7]

... (when can the algorithm stop?)

primes: [2, 3, 5, 7, 11, 13, 17, 19, 23]

public static void sieve(int max) {

// let's write it ...

}

Page 14: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

14

Queue implementations: array

array queue: a queue implemented using an array or array list; queue of size n occupies slots 0 to n-1 in the array

for (int i = 0; i < 80; i += 10) q.enqueue(new Integer(i));[ 0][10][20][30][40][50][60][70][ ][ ]

q.dequeue();[10][20][30][40][50][60][70][ ][ ][ ]

problem: expensive dequeue (must slide) = O(?)

Page 15: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

15

More queue implementations

circular array queue: front element may not be in slot 0; elements can wrap around + cheaper dequeue (no sliding) =

O(?) disadvantages: harder to implement; resizing? how many elements can a circular array hold?

for (int i = 0; i <= 40; i += 10) q.enqueue(new Integer(i));[ 0][10][20][30][40][ ] front = 0, back = 4

for (int i = 0; i < 3; i++) {q.dequeue();}[ ][ ][ ][30][40][ ] front = 3, back = 4

for (int i = 50; i <= 70; i += 10) q.enqueue(new Integer(i));[60][70][ ][30][40][50] front = 3, back = 1

Page 16: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

16

More queue implementations

linked queue: a queue that uses linked nodes or a linked list to hold its elements one of enqueue/dequeue will be

expensive unless we have a myFront and myBack reference, a circularly linked list, etc.

Page 17: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

17

Another idiom: "LIFO" there are also many times where it is useful to

use a list in a way where we always add to the end, and also always remove from the end example: Write code to match brackets in a code file

the last element put into the list will be the first element we take out of the list Last-In, First-Out ("LIFO")

therefore, let's create another new type of collection which is a limited version of List, tailored to this type of usage: a Stack

Page 18: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

18

Abstract data type: Stack stack: a more restricted List with the

following constraints: elements are stored by order of insertion

from "bottom" to "top" items are added to the top only the last element added onto the

stack (the top element) can be accessed or removed

goal: every operation on a stack should be O(1). stacks are straightforward to implement

in several different ways, and are very useful

Page 19: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

19

Operations on a stack push: add an element to the top pop: remove and return the element at the top peek: return (but not remove) top element

pop or peek on an empty stack causes an exception

other operations:isEmpty, size

push(a)push(b)pop()

Page 20: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

20

Stack features ORDERING: maintains order elements were

added(new elements are added to the end by default)

DUPLICATES: yes (allowed) OPERATIONS: add element to end of list

(push), remove element from end of list (pop), examine element at end of list (peek), clear all elements, is empty, get size all of these operations are efficient! O(1)

Page 21: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

21

Stacks in computer science

the lowly stack is one of the most important data structures in all of computer science function/method calls are placed onto a stack compilers use stacks to evaluate expressions stacks are great for reversing things, matching

up related pairs of things, and backtracking algorithms

stack programming problems: reverse letters in a string, reverse words in a line, or

reverse a list of numbers find out whether a string is a palindrome examine a file to see if its braces { } and other

operators match convert infix expressions to postfix or prefix

Page 22: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

22

calculators: postfix or reverse Polish notation.example: 4 5 6 + * 15 +

Method calls stack frame or activation record

func1() { func2(); func3();}func2() { func4();}

func4return varlocals varsarguments

func2return varlocals varsarguments

func1return varlocals varsarguments

Stacks in computer science

Page 23: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

23

Java's Stack class A possible Stack interface:public interface Stack { public void push(Object o); public Object pop(); public Object peek(); public boolean isEmpty(); public int size();} Java does have a java.util.Stack class

with the above methods, so we can use it Java's Stack extends Vector (which is

basically the same as an ArrayList) -- is this good or bad? Why?

Page 24: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

24

Stack programming example

mirror the contents of a queue (named queue)e.g. ["hi", "abc", "bye"] --> ["hi", "abc", "bye", "bye", "abc", "hi"] ... in O(n)

Stack s = new Stack();int queueSize = queue.size();for (int i = 0; i < queueSize; i++) { Object element = queue.dequeue(); s.push(element); queue.enqueue(element);}

while (!s.isEmpty()) { Object element = s.pop(); queue.enqueue(element);}

Page 25: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

25

More stack programming Write a method bracketsMatched that takes

a String and returns true if the { }, [ ], and ( ) match up in nesting and in number.

Write a method equalElements that takes as parameters two stacks and that returns true if the two stacks store the same elements in the same order. Your method will examine the two stacks but should not destroy them; it must return them to their original state before returning. Use one stack as auxiliary storage to solve this problem.

Page 26: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

26

Even more stack programming

Write a method splitStack that takes a stack containing a list of integers and that splits it into negatives and nonnegatives. The numbers in the stack should be rearranged so that all the negatives appear on the bottom of the stack and all the nonnegatives appear on the top of the stack. In other words, if after this method is called you were to pop numbers off the stack, you would first get all the nonnegative numbers (at the top) and then get all the negative numbers (at the bottom). It does not matter what order the numbers appear in as long as all the negatives appear lower in the stack than all the nonnegatives. Use a single queue as auxiliary storage to solve this problem.

Page 27: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

27

Stack implementations: array

array stack: a stack implemented using an array or array list; a stack of size n occupies slots 0 to n-1 in the array

for (int i = 0; i < 80; i += 10) s.push(new Integer(i));[ 0][10][20][30][40][50][60][70][ ][ ]

s.pop();[ 0][10][20][30][40][50][60][ ][ ][ ]

notice that array stack doesn't have efficiency problems like an array queue does

Page 28: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

28

Stack implementations linked stack: a stack implemented using

linked nodes or a linked list the front element of the list is the top of the

stack

push: insert at front pop: remove and return front element peek: return front element clear: set myFront to null

Page 29: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

29

Another collection: Deque deque: a double-ended queue

can add and remove only from either end useful to represent a line where an element

can "cut in" at the front if needed can be implemented with a linked list with

head and tail references (for O(1) add and remove)), or an array with sliding front and back indexes

we will not use deque in this course's programming

Page 30: 1 TCSS 342, Winter 2005 Lecture Notes Stacks and Queues Weiss Ch. 6, pp. 205-209 Weiss Ch. 16, pp. 513-537

30

Stack / queue runtimesOperationadd (push, enqueue)

remove (pop, dequeue)

get particular element (peek)

clear

size

Stack O(1) O(1)

O(1)

O(1)

O(1)

Queue O(1)

O(1)

O(1)

O(1)

O(1)