gpt4 book ai didi

java - 尝试将节点添加到链表中

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

我们从类里面的链表和节点开始,我想我理解它们是如何工作的。但在一方面,我们必须将节点添加到链表中,我遇到了一些让它工作的问题。错误发生在“append”方法中。我的 IDE 没有告诉我太多关于这个问题的信息。

我的类(class)链接列表:

public class LinkedList {
public Node head = null;

public void insert(Node n) {
n.next = head;
head = n;
}

public Node search(int nummer) {
Node current = head;

while (current != null) {
if (current.element == nummer)
return current;
current = current.next;
}
return null;
}

public int count() {
int c = 0;

for (Node n = head; n != null; n = n.next) {
c++;
}
return c;
}

public void append(Node n) {
if (head == null){
head = new Node(n, null);
}
else {
Node p = head;
while (p.a != null){
p = (Node) p.a;
}
p.a = new Node(n, null);}
}
}

我的节点类:

public class Node {
public int element = 0;
public Node next = null;
Object a;

public Node(int e, Node n) {
this.element = e;
this.next = n;
}

public Node(int e) {
this.element = e;
}

}

最佳答案

您将字段a视为指向列表中下一个节点的指针。不是,它实际上是每个列表节点中包含的数据。相反,修改您的 append() 方法以使用 next:

public void append(Node n) {
if (head == null) {
head = new Node(n, null);
}
else {
Node p = head;
// walk down the list from the head until reaching the end
while (p.next != null) {
p = (Node) p.next;
}
// then append the new Node to the end of the list
p.next = n;
}
}

请注意,理想情况下,您的 Node 类应该具有 getter 和 setter 方法。我可能会建议这样的事情:

public class Node {
private int element = 0; // no idea what this is for
private Node next = null;
private Object a;

public Node(int e, Node n) {
this.element = e;
this.next = n;
}

public Node(int e) {
this.element = e;
}

public void setNext(Node next) {
this.next = next;
}

public Node getNext() {
return next;
}

public void setA(Object a) {
this.a = a;
}

public Object getA() {
return a;
}
}

使用 Node 的更新定义,您的 append() 方法将变为:

public void append(Node n) {
if (head == null) {
head = new Node(n, null);
}
else {
Node p = head;
// walk down the list from the head until reaching the end
while (p.getNext() != null) {
p = p.getNext();
}
// then append the new Node to the end of the list
p.setNext(n);
}
}

关于java - 尝试将节点添加到链表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41662432/

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