【发布时间】: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