如何在Java中实现堆栈的反转?

时间:2015-07-28 05:24:14

标签: java

public class StackClass<T> implements StackADT<T>
{
    private int maxStackSize;  //variable to store the
                               //maximum stack size
    private int stackTop;      //variable to point to
                               //the top of the stack
    private T[] list;  //array of reference variables

       //Default constructor
       //Create an array of the size 100 to implement the stack.
       //Postcondition: The variable list contains the base
       //               address of the array, stackTop = 0,
       //               and maxStackSize = 100.
    public StackClass()
    {
        maxStackSize = 100;
        stackTop = 0;         //set stackTop to 0
        list = (T[]) new Object[maxStackSize]; //create the array
    }//end default constructor

       //Constructor with a parameter
       //Create an array of the size stackSize to implement the
       //stack.
       //Postcondition: The variable list contains the base
       //               address of the array, stackTop = 0,
       //               and maxStackSize = stackSize.
    public StackClass(int stackSize)
    {
        if (stackSize <= 0)
        {
            System.err.println("The size of the array to "
                             + "implement the stack must be "
                             + "positive.");
            System.err.println("Creating an array of the size 100.");

            maxStackSize = 100;
        }
        else
            maxStackSize = stackSize; //set the stack size to
                                      //the value specified by
                                      //the parameter stackSize
        stackTop = 0;    //set stackTop to 0
        list = (T[]) new Object[maxStackSize]; //create the array
    }//end constructor

       //Method to initialize the stack to an empty state.
       //Postcondition: stackTop = 0
    public void initializeStack()
    {
        for (int i = 0; i < stackTop; i++)
            list[i] = null;

        stackTop = 0;
    }//end initializeStack

       //Method to determine whether the stack is empty.
       //Postcondition: Returns true if the stack is empty;
       //               otherwise, returns false.
    public boolean isEmptyStack()
    {
        return (stackTop == 0);
    }//end isEmptyStack

       //Method to determine whether the stack is full.
       //Postcondition: Returns true if the stack is full;
       //               otherwise, returns false.
    public boolean isFullStack()
    {
        return (stackTop == maxStackSize);
    }//end isFullStack

       //Method to add newItem to the stack.
       //Precondition: The stack exists and is not full.
       //Postcondition: The stack is changed and newItem
       //               is added to the top of stack.
       //               If the stack is full, the method
       //               throws StackOverflowException
    public void push(T newItem) throws StackOverflowException
    {
        if (isFullStack())
            throw new StackOverflowException();

        list[stackTop] = newItem; //add newItem at the
                                  //top of the stack
        stackTop++;               //increment stackTop
    }//end push

       //Method to return a reference to the top element of
       //the stack.
       //Precondition: The stack exists and is not empty.
       //Postcondition: If the stack is empty, the method
       //               throws StackUnderflowException;
       //               otherwise, a reference to the top
       //               element of the stack is returned.
    public T peek() throws StackUnderflowException
    {
        if (isEmptyStack())
            throw new StackUnderflowException();

        return (T) list[stackTop - 1];
    }//end peek

       //Method to remove the top element of the stack.
       //Precondition: The stack exists and is not empty.
       //Postcondition: The stack is changed and the top
       //               element is removed from the stack.
       //               If the stack is empty, the method
       //               throws StackUnderflowException
    public void pop() throws StackUnderflowException
    {
        if (isEmptyStack())
           throw new StackUnderflowException();

        stackTop--;       //decrement stackTop
        list[stackTop] = null;
    }//end pop


}

我试图实现一个reverseStack操作,它以相反的顺序将堆栈元素复制到另一个堆栈上。到目前为止,我已经提出了以下内容......

public void reverseStack(StackClass<T> otherStack)
        {
           StackClass<T> newStack = new StackClass<T>();

           StackObj obj = null;
           while ( (obj = this.pop()) != null ) {
                      otherStack.push(obj);
                      newStack.push(obj);
           }

           // Now push back from newStack to this stack
           while ( (obj = newStack.pop() ) != null ) {
                     this.push(obj);
           }
        }

但是我的代码部分存在问题

StackObj obj = null;
while ( (obj = this.pop()) != null ) {
    otherStack.push(obj);
    newStack.push(obj);
   }

因为从未定义过StackObj类。然而,我不知道还有什么我可以定义obj,因为我的pop程序没有返回值。有什么想法吗?

谢谢(没有这不是家庭作业......我试图通过练习自己学习Java。)

2 个答案:

答案 0 :(得分:1)

您可以直接使用类型T:

public StackClass<T> reverseStack()
    {
       StackClass<T> newStack = new StackClass<T>();

       T obj = null;
       while ( (obj = this.pop()) != null ) {
                  newStack.push(obj);
       }

       return newStack; //Shallow reversed stack
    }

由于您的堆栈包含T类型的对象,您还应该像T一样威胁它们。

要记住的事情Deep vs Shallow Copy。你正在做一个浅薄的副本,这是你想要的吗? :)

答案 1 :(得分:0)

我认为最简单的方法是创建一个新数组并以相反的顺序插入它们。下面的代码执行此操作,但它也返回一个新的StackClass,保持当前的一个不变。它通过为private创建一个StackClass构造函数来实现这一点,它将数组直接传递给类。

/**
 * Internal constructor
 * @param list
 * @param stackTop
 */
private StackClass(T[] list, int stackTop) {
    this.list = list;
    this.maxStackSize = list.length;
    this.stackTop = stackTop;
}

/**
 * Reverses the current stack and returns it. The current instance remains unchanged
 * @return
 */
public StackClass<T> reverse() {
    // create our new stack
    T[] newList = (T[]) new Object[maxStackSize];
    // loop through the current stack in reverse pushing them onto the new stack in the correct order
    for(int i=stackTop-1;i>=0;i--) {
        newList[(stackTop-1)-i] = list[i];
    }
    // create our new stack for returning
    return new StackClass<T>(newList, stackTop);
}

现在,如果你想编写一个改变当前堆栈的方法,那就不要远离这段代码了。