Created
April 2, 2015 18:49
-
-
Save kevinmichaelchen/27dde22593a3f9baf8c9 to your computer and use it in GitHub Desktop.
Basic Stack Implementation (Java)
This file contains hidden or 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
public class BasicStack { | |
private Object[] array = null; | |
private boolean debug = false; | |
public BasicStack() { | |
this(10); | |
} | |
public BasicStack(int capacity) { | |
array = new Object[capacity]; | |
} | |
/** @param debug If true, print for each pop/push operation */ | |
public BasicStack(int capacity, boolean debug) { | |
this(capacity); | |
this.debug = debug; | |
} | |
public void push(Object t) { | |
for (int i = 0; i < array.length; i++) { | |
if (isEmptyAt(i)) { | |
array[i] = t; | |
return; | |
} | |
} | |
resize(t); | |
if (debug) { | |
this.print(); | |
} | |
} | |
private void resize(Object objectToBeInserted) { | |
int pos = array.length; | |
Object[] newArray = new Object[array.length * 2]; | |
for (int i = 0; i < array.length; i++) { | |
newArray[i] = array[i]; | |
} | |
newArray[pos] = objectToBeInserted; | |
array = newArray; | |
} | |
public Object pop() { | |
Object result = null; | |
for (int i = array.length - 1; i >= 0; i--) { | |
if (isEmptyAt(i)) continue; | |
else { | |
result = array[i]; | |
array[i] = null; | |
break; | |
} | |
} | |
if (debug) { | |
this.print(); | |
} | |
return result; | |
} | |
private boolean isEmptyAt(int index) { | |
return array[index] == null; | |
} | |
@Override | |
public String toString() { | |
String s = "| "; | |
for (int i = 0; i < array.length; i++) { | |
s += (array[i] + " | "); | |
if (i == array.length - 1) { | |
s += "\n"; | |
} | |
} | |
return s; | |
} | |
public void print() { | |
System.out.println(this); | |
} | |
public static void main(String[] args) { | |
BasicStack stack = new BasicStack(3); | |
stack.push(1); stack.print(); | |
stack.push(2); stack.print(); | |
stack.push(3); stack.print(); | |
stack.push(4); stack.print(); | |
stack.push(5); stack.print(); | |
stack.pop(); stack.print(); | |
System.out.println("ROUND 2"); | |
stack = new BasicStack(2, true); | |
stack.push(1); | |
stack.push(2); | |
stack.push(3); | |
stack.push(4); | |
stack.push(5); | |
stack.pop(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment