使用“ for”循环打印堆栈

时间:2018-10-21 20:27:15

标签: java stack

我正在尝试反向打印堆栈S的元素(使用“ for”循环),但到目前为止我还没有成功。

我已经很容易用“ pop”来做到这一点,但是第二种方式使我回避了。我的“ pop”解决方案在代码末尾被注释掉了。

任何帮助将不胜感激。

PS。这段代码大多数与问题无关,但是如果我知道可以切的内容和切入的地方,我可能根本不需要帮助。抱歉。

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[], K[];      // 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");

//      Stack K is created by popping elements of Stack S from the top.
//      This reverses the order.
//
//      Stack K = new SimpleArrayStackofchars();
//      while (!S.isEmpty()) {
//          K.push(S.pop());
//        }
//      while (!K.isEmpty()) {
//            System.out.println(K.pop());
//        }

    while (!S.isEmpty()) {
        System.out.println(S.pop());
    }
}

}

1 个答案:

答案 0 :(得分:0)

Not really sure about what you need that for loop for, but this should produce the same result:
 Stack K = new SimpleArrayStackofchars();
 for (int i = 0, i < S.size(); i++) {
     K.push(S.pop());
 }
 for (int i = 0, i < K.size(); i++) {
     System.out.println(K.pop());
 }