链接堆栈实现

时间:2016-02-08 20:59:07

标签: java

我的问题在于pop和尺寸堆栈。我知道pop删除了最高值并将其替换为下一个值。我该怎么做?

此外,正确的方法是什么?

代码:

    public int pop()
    { 

          if (isEmpty())
            throw new RuntimeException("Pop attempted on an empty stack");
        else
        {
            return  m_top.value  ;  
        }

    }

    // return the size of the stack
    public int size()
    {       

          if (m_top == null)
        return 0;
        else
        return m_top.value; 
    }

2 个答案:

答案 0 :(得分:0)

能够随时检索堆栈大小的一种好方法是在内部维护它。

正如@Peter Lawrey在评论中所建议的那样,在JDK中寻找真​​正的实现可能是一个很好的灵感来源,即使它在开始时可能是可怕的。 例如,您将看到LinkedList中的size方法以这种方式实现,为每个链接列表实例维护内部size属性。

对于pop方法,您需要准确了解如何实现堆栈。对于pop,您至少需要能够从堆栈顶部的项目中检索上一个项目。 我看到你在内部使用Node对象,你创建了这个类吗? 这是家庭作业的一部分吗?如果再次仔细查看链表实现,您会发现它还使用一个Node对象(当然不是巧合......),它存储对其下一个和上一个对象的引用。

答案 1 :(得分:0)

  

我知道pop删除了最高值并将其替换为下一个值。我该怎么做?

您需要将m_top变量重新分配给它link

public int pop() {

    if (isEmpty())
        throw new RuntimeException("Pop attempted on an empty stack");
    else {
        int top_value = m_top.value;
        // Move the top off the "stack" by moving the pointer
        m_top = m_top.link;
        return top_value;
    }
}
  

获得大小的方法?

您可以计算列表中Node的数量,而不是返回顶部value的{​​{1}}。正如评论中所提到的,这不是“最有效的方式”。

Node
相关问题