遍历链表的实现 Java
Iterating through an implementation of a Linked List Java
所以我阅读了几篇关于这个主题的帖子,但它们都提到了遍历 Java 已经实现的链表;例如,LinkedList<String> list = new LinkedList<String>();
。然后继续说使用for循环遍历链表。但是,我正在尝试实现自己的链表,但不确定如何遍历它们。换句话说,我有以下代码:
class Node {
private Node next = null;
private int data;
public Node(int d) {
data = d;
}
void appendToTail(int d) {
Node end = new Node(d);
Node n = this;
while(n.next != null) {
n = n.next;
}
n.next = end;
}
void print() {
Node n = this;
while(n.next != null) {
System.out.println(n);
n = n.next;
}
}
public static void main(String [] args) {
Node x = new Node(4);
x.appendToTail(5);
x.print();
}
}
我写的print()
函数是我试图遍历链表的努力。但是,它不起作用。鉴于您自己的链表实现,有人知道如何遍历链表吗?
改变
while(n.next != null)
到
while(n != null)
因为在循环中您正在打印当前 node n
然后通过以下方式将其指向下一个 node: n = n.next;
您应该检查当前节点是否为null
,而不是下一个节点。因为那样你会错过列表的最后一个节点,所以 next
部分将是最后一个节点的 null
并且循环不会执行。
您需要打印节点的 data
部分。您还没有为您的节点 class.
定义 toString
方法
void print() {
Node n = this;
while(n != null) {
System.out.println(n.data);
n = n.next;
}
}
你可以为你的Node
class定义如下toString
,然后你可以直接在System.out
语句中打印Node
对象。
@Override
public String toString() {
return "Node{" +
", data=" + data +
'}';
}
您应该检查 n
是否为空,而不是 n.next()
::
while(n != null)
但是您拥有 for
循环的所有方面(初始状态、终止条件和迭代表达式),因此最好将其表示为 for
循环:
for (Node n = this; n != null; n = n.next)
System.out.println(n.data);
所以我阅读了几篇关于这个主题的帖子,但它们都提到了遍历 Java 已经实现的链表;例如,LinkedList<String> list = new LinkedList<String>();
。然后继续说使用for循环遍历链表。但是,我正在尝试实现自己的链表,但不确定如何遍历它们。换句话说,我有以下代码:
class Node {
private Node next = null;
private int data;
public Node(int d) {
data = d;
}
void appendToTail(int d) {
Node end = new Node(d);
Node n = this;
while(n.next != null) {
n = n.next;
}
n.next = end;
}
void print() {
Node n = this;
while(n.next != null) {
System.out.println(n);
n = n.next;
}
}
public static void main(String [] args) {
Node x = new Node(4);
x.appendToTail(5);
x.print();
}
}
我写的print()
函数是我试图遍历链表的努力。但是,它不起作用。鉴于您自己的链表实现,有人知道如何遍历链表吗?
改变
while(n.next != null)
到
while(n != null)
因为在循环中您正在打印当前 node n
然后通过以下方式将其指向下一个 node: n = n.next;
您应该检查当前节点是否为null
,而不是下一个节点。因为那样你会错过列表的最后一个节点,所以 next
部分将是最后一个节点的 null
并且循环不会执行。
您需要打印节点的 data
部分。您还没有为您的节点 class.
toString
方法
void print() {
Node n = this;
while(n != null) {
System.out.println(n.data);
n = n.next;
}
}
你可以为你的Node
class定义如下toString
,然后你可以直接在System.out
语句中打印Node
对象。
@Override
public String toString() {
return "Node{" +
", data=" + data +
'}';
}
您应该检查 n
是否为空,而不是 n.next()
::
while(n != null)
但是您拥有 for
循环的所有方面(初始状态、终止条件和迭代表达式),因此最好将其表示为 for
循环:
for (Node n = this; n != null; n = n.next)
System.out.println(n.data);