Quiz_1_ans - public interface Queue<AnyType> {...

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

View Full Document Right Arrow Icon
Quiz #1 Sep. 28, 2009 Student ID: Name: A stack must provide the following operations. We make use of an interface in Java. public interface Stack<AnyType> { void clear(); boolean isEmpty(); AnyType top(); AnyType pop(); void push(AnyType x); } We will have to define a class, for instance DsStack, that implements the Stack interface using Array. public class DsStack<AnyType> implements Stack<AnyType> { public DsStack() { clear(); } public void clear() { iData = (AnyType []) new Object[INITIAL_SIZE]; iTop = -1; } public boolean isEmpty() { return (iTop < 0); } public AnyType top() { if (iTop < 0) throw new StackUnderflowException(); return iData[iTop]; } public AnyType pop() { if (iTop < 0) throw new StackUnderflowException(); return iData[iTop--]; } public void push(AnyType x) { if (iTop + 1 >= iData.length) throw new StackOverflowException(); iData[++iTop] = x; } private static final int = INITIAL_SIZE = 1000000; private AnyType [] iData; private int iTop; }
Background image of page 1

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

View Full DocumentRight Arrow Icon
Now, define the interface for a queue providing the operation:
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: public interface Queue<AnyType> { boolean isEmpty(); AnyType front(); void enqueue(AnyType x); AnyType dequeue(); } Also, define a class, for instance DsQueue, that implements the Queue interface using Array. public class DsQueue<AnyType> implements Queue<AnyType> { public Queue() { iData = (AnyType []) new Object[INITIAL_SIZE]; iEnd = -1; } public boolean isEmpty() { return (iEnd < 0); } public void enqueue(AnyType x); { if (iEnd + 1 >= iData.length) throw new QueueOverflowException(); iData[++iEnd] = x; } public AnyType dequeue(); { if (isEmpty()) throw new EmptyQueueException(); AnyType t = iData[iFRONT]; for (i=1; i>iEnd; i++) { iData[i-1] = iData[i]; } iEnd--; return t; } public AnyType front(){ if (isEmpty()) throw new EmptyQueueException(); return iData[iFRONT]; } private static final int INITIAL_SIZE = 1000000; private static final int IFRONT = 0; private AnyType [] iData; private int iEnd; }...
View Full Document

This note was uploaded on 04/20/2010 for the course CS CS206 taught by Professor Lee during the Fall '09 term at 카이스트, 한국과학기술원.

Page1 / 2

Quiz_1_ans - public interface Queue<AnyType> {...

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

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