Skip to content

Instantly share code, notes, and snippets.

@ThomsonTang
Created January 10, 2013 10:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThomsonTang/4500913 to your computer and use it in GitHub Desktop.
Save ThomsonTang/4500913 to your computer and use it in GitHub Desktop.
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());
}
}
@mrmagic048
Copy link

Review before 7/15
Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment