I am trying to implement a stack where one can push to the front and to the back of the stack. However, my implementation is very slow. Can anyone help me think of a better method? Thank you!
public class Pch11_x1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
DoubleStack s = new DoubleStack();
s.pushFront("b");
s.pushFront(new Character('c'));
s.pushBack(new Integer(1));
for (int i = 0; i < s.getSize() + 1; i++) {
System.out.println(s.peekFront(i));
}
for (int i = 0; i < 30000001; i++) {
Object t = s.peekFront(0);
s.popFront(1);
s.pushBack(t);
}
for (int i = 0; i < s.getSize() + 1; i++) {
System.out.println(s.peekFront(i));
}
for (int i = 0; i < 30000001; i++) {
Object t = s.peekBack(0);
s.popBack(1);
s.pushFront(t);
}
for (int i = 0; i < s.getSize() + 1; i++) {
System.out.println(s.peekFront(i));
}
}
}
class DoubleStack {
private Object[] data;
private int size;
private final static int INIT_CAPACITY = 16;
public DoubleStack() {
data = new Object[INIT_CAPACITY];
size = 0;
}
// push obj onto the front of the list
public void pushFront(Object obj) {
if (size == data.length) {
Object[] newData = new Object[2 * data.length];
System.arraycopy(data, 0, newData, 0, data.length);
data = newData;
}
data[size] = obj;
size++;
}
// pop n Object's off the front of the list
public void popFront(int n) {
if (n < 0) {
return;
}
if (n > size) {
n = size;
}
size -= n;
return;
}
// return the object that is n from the front
// of the list (sizeing from 0)
public Object peekFront(int n) {
if (n < 0) {
return null;
} else {
return data[size - n];
}
}
// push obj onto the back of the list
public void pushBack(Object obj) {
if (size == data.length) {
Object[] newData = new Object[2 * data.length];
System.arraycopy(data, 0, newData, 0, data.length);
data = newData;
}
Object[] newData = new Object[data.length + 1];
System.arraycopy(data, 0, newData, 1, data.length);
data = newData;
data[0] = obj;
}
// pop n Object's off the back of the list
public void popBack(int n) {
if (n < 0) {
return;
}
if (n > size) {
n = size;
}
size -= n;
return;
}
// return the object that is n from the back
// of the list (sizeing from 0)
public Object peekBack(int n) {
if (n < 0) {
return null;
} else {
return data[0 + n];
}
}
// return the size of the list
public int getSize() {
return size;
}
}