Created
January 10, 2013 10:06
-
-
Save ThomsonTang/4500913 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package datastructure.stackqueue; | |
interface Stack { | |
void push(Object obj); | |
Object pop(); | |
boolean isEmpty(); | |
} | |
class ArrayStack implements Stack { | |
private Object[] theArray; | |
private int topOfStack; | |
private static final int DEFAULT_CAPACITY = 10; | |
public ArrayStack() { | |
theArray = new Object[DEFAULT_CAPACITY]; | |
topOfStack = -1; | |
} | |
public boolean isEmpty() { | |
return topOfStack == -1; | |
} | |
public void push(Object obj) { | |
if(!isFull()) { | |
theArray[++topOfStack] = obj; | |
} | |
} | |
public Object pop() { | |
if(!isEmpty()) { | |
return theArray[topOfStack--]; | |
} else { | |
return null; | |
} | |
} | |
public boolean isFull() { | |
return (topOfStack == theArray.length); | |
} | |
} | |
public class StackQueue { | |
ArrayStack inStack = new ArrayStack(); | |
ArrayStack outStack = new ArrayStack(); | |
public void enQueue(Object obj) { | |
inStack.push(obj); | |
} | |
public Object deQueue() { | |
if(outStack.isEmpty()) { | |
while(!inStack.isEmpty()) { | |
outStack.push(inStack.pop()); | |
} | |
} | |
return outStack.pop(); | |
} | |
public static void main(String[] args) { | |
StackQueue queue = new StackQueue(); | |
queue.enQueue("first"); | |
queue.enQueue("second"); | |
queue.enQueue("third"); | |
queue.enQueue("fourth"); | |
System.out.println("1." + queue.deQueue()); | |
System.out.println("2." + queue.deQueue()); | |
System.out.println("3." + queue.deQueue()); | |
System.out.println("4." + queue.deQueue()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Review before 7/15
Thanks