set3_sol

set3_sol - CS112 Summer 2011: Problem Set 3 Stack, Queue,...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
CS112 Summer 2011: Problem Set 3 Stack, Queue, Smart Auto-Expanding Array ------------------------------------------------------------------------ 1. Programming Problem P7.3, page 227 of the textbook. Suppose that the Stack class consisted only of the three methods push, pop, and isEmpty: public class Stack<T> { ... public Stack() { . .. } public void push(T item) { . .. } public T pop() throws NoSuchElementException { . .. } public boolean isEmpty() { . .. } } Implement the following "client" method (i.e. /not/ in the Stack class, but in the program that uses a stack): public int size(Stack<String> S) { // COMPLETE THIS METHOD } to return the number of items in a given stack S. Analyze this method for worst case big /O/ running time, following these steps: * Identify the basic unit-time operations that contribute to the running time. You may assume that the constructor, as well as the push, pop, and isEmpty methods are all worst case /O(1)/ running time. * Count the number of times each of these basic operations are executed in the worst case, and compute the total * Convert the total number of basic operations to big /O/ *SOLUTION* Create another, temporary stack. Pop all items from input to temp stack, count items as you go. When all done, push items back from temp stack to input, and return count. public int size(Stack<String> S) { // COMPLETE THIS METHOD Stack<T> temp = new Stack<T>(); int count=0; while (!S.isEmpty()) { temp.push(S.pop()); count++; } while (!temp.isEmpty()) { S.push(temp.pop()); } return count; } * Basic operators are push, pop, and isEmpty. (Constructor is only used once, so can be ignored since it is independent of the
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
input stack size.) * Each item in the stack is popped and pushed two times. With each push or pop, there is also a check for empty, and an additional check to terminate the loop. If the length of the input stack is /n/, the total units of time taken will be /2n/ (pushes) + /2n/ (pops), + /2n+2/ (empty checks) = /6n+2/ * O(/n/) ------------------------------------------------------------------------ 2. You are given a Queue class with the following public interface:
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This document was uploaded on 11/01/2011 for the course 198 112 at Rutgers.

Page1 / 5

set3_sol - CS112 Summer 2011: Problem Set 3 Stack, Queue,...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online