猿问

如何在java中创建一个通用堆栈弹出方法

我目前正在开发一个 Stack 项目,我正在创建一个通用的 Stack 类。我一直在为此寻找堆栈溢出,但找不到。我需要帮助在我的代码中创建一个 pop 方法。


这是我到目前为止所拥有的:


public class Stack<E>

{

public static final int DEFAULT_CAPACITY = 10;

private E [] elementData;

private int size;


@SuppressWarnings("unchecked")

public Stack()

{

    this.elementData = (E[]) new Object[DEFAULT_CAPACITY];

}

@SuppressWarnings("unchecked")

public Stack(int capacity)

{

    if(capacity < 0)

    {

        throw new IllegalArgumentException("capacity " + capacity);

    }

    this.elementData = (E[]) new Object[capacity];

}

public boolean isEmpty()

{

    if(size == 0)

    {

        return true;

    }

    else

    {

        return false;

    }

}

/*

The push method should add its parameter to the top of the stack.

*/

public void push(E item)

{

    ensureCapacity(size+1);

    elementData[size] = item;

    size++;

}

private void ensureCapacity(int capacity)

    {

    if(elementData.length < capacity)

    {

        int newCapacity = elementData.length * 2 + 1;

        elementData = Arrays.copyOf(elementData, newCapacity);

    }

}

我在这里需要帮助。我需要让 pop 方法删除并返回堆栈顶部的元素。如果不存在任何项目,它应该抛出“EmptyStackException”。


    public E pop()

    {

    if(isEmpty())

    {

        throw EmptyStackException

    }

    else

    {


    }

}

}


呼啦一阵风
浏览 79回答 2
2回答

哈士奇WWW

我想通了,我把功劳归功于@ScaryWombat。代码是:public E pop(){&nbsp; &nbsp; if(isEmpty())&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; throw new EmptyStackException();&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return elementData[--size];&nbsp; &nbsp; }}

梵蒂冈之花

public E pop()&nbsp;{&nbsp; &nbsp; E item;&nbsp; &nbsp; if(isEmpty())&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; throw new EmptyStackException();&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; item = elementData[size];&nbsp; &nbsp; &nbsp; &nbsp; size--;&nbsp; &nbsp; }&nbsp; &nbsp; return item;}您需要使返回变量等于堆栈数组的顶部,然后递减堆栈数组。此外,您需要通过设置 size=0 来初始化堆栈。
随时随地看视频慕课网APP

相关分类

Java
我要回答