package SimpleArrayStackofchars;
public class SimpleArrayStackofchars implements Stack
{
protected int capacity; // The actual capacity of the stack array
public static final int CAPACITY = 2; // default array capacity
protected Object S[]; // Generic array used to implement the stack
protected int top = -1; // index for the top of the stack (-1 = empty stack)
public SimpleArrayStackofchars()
{
this(CAPACITY); // default capacity
}
public SimpleArrayStackofchars(int cap)
{
capacity = cap;
S = new Object[capacity];
}
public int size()
{
return (top + 1);
}
public boolean isEmpty()
{
return (top == -1);
}
public void push(Object element) throws FullStackException
{
if(size() == capacity)
{
//throw new FullStackException
("Stack is full. Stack size max is "+ capacity);
/*can replace previous line with code to double stack size
*/
doubleArray();
}
S[++top] = element;
}
public Object top() throws EmptyStackException
{
if (isEmpty())
throw new EmptyStackException("Stack is empty.");
return S[top];
}
public Object pop() throws EmptyStackException
{
Object element;
if (isEmpty())
throw new EmptyStackException("Stack is empty.");
element = S[top];
S[top--] = null; // dereference S[top] for garbage collection.
return element;
}
private void doubleArray()
{
Object [ ] newArray;
System.out.println("Stack is full (max size was "+capacity+"). Increasing to "+(2*capacity));
//double variable capacity
capacity = 2*capacity;
newArray = new Object[ capacity ];
for(int i = 0; i < S.length; i++)
newArray[ i ] = S[ i ];
S = newArray;
}
public static void main(String[] args)
{
Stack S = new SimpleArrayStackofchars();
S.push("1");
S.push("2");
S.push("3");
S.push("4");
S.push("5");
S.push("6");
while (!S.isEmpty())
{
System.out.println(S.pop());
}
}
}
所以我有上面的代码,当我运行它时,它打印输出。不过,我还有一个问题,我不明白如何去做。以相反的顺序打印阵列元素
这是问题:重新编写main方法,以便调用另一个称为reverseUsingPop的方法,该方法将采用字符数组并使用pop方法以相反的顺序打印数组元素。
太好了,你给了我们很多大多数不相关的代码,你从你的任务中复制粘贴了这个问题。你正在努力的是什么? –
我不知道如何去做reverseUsingPop方法。这对我来说成了一个问题 – user5500578
http://stackoverflow.com/help/how-to-ask –