【问题标题】:Return top element in a stack返回栈顶元素
【发布时间】:2020-06-06 22:46:08
【问题描述】:

我正在努力使用 top() 方法,该方法应该检索堆栈的顶部元素,或者如果此堆栈为空则返回 null 并返回堆栈的顶部元素。如何修复循环?

public class Stack<E> implements IStack<E> {
Node head;
    public E top() {

        if (head == null)
            return null;

        Node<E> tempNode = head;

        for (int i = 0; i < size; i++) {
            if (tempNode.getmNextNode() == null) {
                tempNode.getmElement();
            }
            tempNode = tempNode.getmNextNode();
        }
        return tempNode.getmElement();
    }
}

我的节点类:

public class Node<E> {
    private E mElement;
    private Node<E> mNextNode;

    Node(E data) {
        this.setmElement(data);
    }

    public E getmElement() {
        return this.mElement;
    }

    public void setmElement(E element) {
        this.mElement = element;
    }

    public Node<E> getmNextNode() {
        return this.mNextNode;
    }

    public void setmNextNode(Node<E> node) {
        this.mNextNode = node;
    }
}

【问题讨论】:

  • 您到底遇到了什么错误?那是你的完整代码吗? “头”和“大小”在哪里定义?
  • head 不会是栈顶吗?如果不是,为什么不呢?为什么需要跟踪堆栈的底部?
  • 可能应该包含您的 push 代码,以向我们提示您的实施 - 但很可能您只需要返回 head

标签: java indexing methods linked-list


【解决方案1】:
public E top() {
    if (head == null)
        return null;
    Node<E> tempNode = head;
    while(tempNode.getmNextNode()!=null) {
        tempNode = tempNode.getmNextNode();
    }
    return tempNode.getmElement();
}

【讨论】:

  • 谢谢,我试过了但是报错Required type: E for return head.getmElement()
  • 这不应该给你这样的错误。您的程序中的其他地方有问题。发布完整代码以获得更多帮助。
  • 我必须在 Node 头中添加 ;所以它现在没有给我这个错误。我猜 head 是堆栈的底部,因为它返回元素 0
  • @Natalie_94 - 我刚刚更新了我的答案。我希望,它现在对你有用。
【解决方案2】:

您的top() 方法应该将最后一个推入的元素返回到堆栈中,而不是第一个。当推送一个新元素时,head 被引用到这个元素。因此,head 是顶部元素,然后将由您的方法返回。

public class Stack<E> implements IStack<E>{

    public E top() {
    if(head==null){
    throw new StackEmptyException();
     }
    return head.getmElement();
     }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多