gpt4 book ai didi

java - 调用时无法识别 LinkedList 中的第一个节点数据

转载 作者:太空宇宙 更新时间:2023-11-04 09:46:55 25 4
gpt4 key购买 nike

我使用链表从头开始创建了一个堆栈数据结构。似乎 push() 正确,因为我可以使用 first.data 的显示方法,并且它显示列表。但是当我使用peek()时,我得到一个NoSuchElementException,因为有一个if语句if(first == null),但first不应该是null

我不知道如何以不同的方式解决这个问题。

public class StackNew implements Stack{ //Stack is an interface given by my professor

private int size;

private class Node {
public Object data;
public Node next;
public Node(Object data, Node next) {
this.data = data;
this.next = next;
}
}

private Node first = null;

public void push(Object newElement) {
first = new Node(newElement, first);
size++;

}
public Object peek(){
if (first == null) {
throw new NoSuchElementException();
}
return first.data;
}
public void display() {
Node previous = null;
while(first != null) {
System.out.println((first.data));
previous = first;
first = first.next;
}
}
public static void main(String args[]) {
StackNew stack = new StackNew();
stack.push("java");
stack.push(1);
stack.push("code");

stack.display();
System.out.println(stack.isEmpty());
stack.peek();

}

当我尝试使用 peek() 方法时,第一个节点为 null,而它应该包含“code”。

最佳答案

在您的代码中,您会注意到仅当您调用 display 方法时才会收到错误。

这是因为在您的实现中,您将 first 覆盖为 first.next,它最终在 while 循环的最后一次迭代中变为 null。因此,您需要一个新指针来跟踪当前元素,并在不影响 first 指针的情况下前进到下一个元素。

因此您需要将 display 方法更正为:

 public void display() {
Node current = first;
while(current != null) {
System.out.println((current.data));
current = current.next;
}
}

这里一个新的指针current将跟踪当前元素,并在while循环中连续打印元素。

代码中的一些其他问题(如果您尝试扩展java.util.Stack):

  1. 您正在尝试实现 Stack 类,但实际上您应该扩展它。
  2. 为了使用 Stack 类中的 isEmpty(),您需要在 push() 方法中增加 elementCount++; 而不是 size。由于 isEmpty() 检查从 Stack 类继承的 elementCount
  3. push 的返回类型不应为 void,而应返回参数。 (根据Stack类的Java doc)。

    @Override
    public Object push(Object newElement) {
    first = new Node(newElement, first);
    elementCount++;
    return newElement;
    }

关于java - 调用时无法识别 LinkedList 中的第一个节点数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55311525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com