Download presentation

1
**TCSS 342, Winter 2005 Lecture Notes**

Stacks and Queues Weiss Ch. 6, pp Weiss Ch. 16, pp

2
**Review: List method runtimes**

Operation add to start of list add to end of list add at given index clear get find index of an object remove first element remove last element remove at given index set size toString Array list O(n) O(1) Linked list

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)

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?

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

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)

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

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)

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

10
**Queue programming example**

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) Queue q = new LinkedQueue(); while (!list.isEmpty()) q.enqueue(list.removeFirst()); while (!q.isEmpty()) { Object element = q.dequeue(); list.add(element); list.add(element); }

11
**Queue programming example**

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) int size = queue.size(); for (int i = 0; i < size; i++) { Object element = queue.dequeue(); queue.enqueue(element); queue.enqueue(element); }

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]

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 ... }

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(?)

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) [60][70][ ][30][40][50] front = 3, back = 1 show front, back indexes

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.

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

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

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()

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)

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 inbox and outbox at work are stacks connect-four are stacks of chips

22
**Stacks in computer science**

calculators: postfix or reverse Polish notation. example: * Method calls stack frame or activation record func1() { func2(); func3(); } func4 return var locals vars arguments func2 func1 func2() { func4(); }

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?

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();

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.

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.

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

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

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

30
**Stack / queue runtimes Operation add (push, enqueue)**

remove (pop, dequeue) get particular element (peek) clear size Stack O(1) Queue

Similar presentations

© 2020 SlidePlayer.com Inc.

All rights reserved.

To make this website work, we log user data and share it with processors. To use this website, you must agree to our Privacy Policy, including cookie policy.

Ads by Google