0
public class ArrayStackImpl<AnyType> implements Stack<AnyType>
{
    // large array limit  to store the stack
    public final int LIMIT = 10000000;

    // the actual storage with a pointer to the top of the stack
    private AnyType[] vals = (AnyType[]) new Object[LIMIT];
    private int topPointer = -1;

    // return the top of the stack by pointing to top point
    public AnyType top()
    {
        return vals[topPointer];
    }

    // return the top and reduce the top pointer
    public AnyType pop()
    {
        AnyType tmp = top();
        topPointer--;
        return tmp;
    }

    // increase the top pointer and add the data
    public void push(AnyType data)
    {
        topPointer++;
        vals[topPointer] = data;
    }

    // returns true if the stack is empty
    public boolean empty()
    {
        return topPointer == -1;
    }
}

public void stackArrange(ArrayList list1, ArrayList list2)
{
    ArrayStackImpl<Integer> s = new ArrayStackImpl<Integer>();

    if (list1.isEmpty()) {
        throw new IllegalArgumentException("Array is Empty");
    }
    if (s.empty()) {
        s.push((Integer) list1.get(list1.size() - 1));
    }
    for (int i = list1.size() - 2; i >= 0; i--) {
        int e = (Integer) list1.get(i);
        if (e >= s.top()) {
            while (!s.empty()) {
                list2.add(s.pop());
            }
            s.push(e);
        }
        else {
            s.push(e);
        }
    }
}

我在弹出元素时遇到问题。如果元素大于然后,我需要比较堆栈中的元素,弹出堆栈中的元素并压入当前元素。so 比如从这个arraylist的后面留 1, 4, 3, 2, 7, 3, 6, 4 如果栈是空的,把4压入栈6大于4所以pop 4,把6压入栈. 3 小于 push 3 入栈。7 大于 3,所以 pop 3 和 pop 6 使用 while 循环。

当我调试它时,问题就来了。即使顶部指针是-1,7也会覆盖堆栈中的6。

我在while循环中的错误是什么?

4

0 回答 0