gpt4 book ai didi

java - 在java中显示链表

转载 作者:行者123 更新时间:2023-12-01 10:17:04 26 4
gpt4 key购买 nike

我正在做一项作业,需要根据给定的模板创建一个链接列表。对于创建的每个新节点,我需要打印出更新的列表。然而,到目前为止,我一直对如何打印链接列表感到困惑。谁能弄清楚我做错了什么吗?我目前所拥有的只是打印出已创建的数字,后跟空格,而不是到目前为止的整个列表。

NumberList.java

import java.util.*;

public class NumberList {

private Node head;

public NumberList() {
}
public void insertAtHead(int x) {
Node newNode = new Node(x);

if (head == null)
head = newNode;
else {
newNode.setNext(head);
head = newNode;
}
}
public void insertAtTail(int x) {
}
public void insertInOrder(int x) {
}
public String toString() {
Node tmp = head;

String result = "";
while (tmp.getNext() != null) {
result += tmp.toString() + " ";
}

return result;
}
//---------------------

// test methods

//---------------------

public static void testInsertAtHead() {

Random r = new Random();
int n = 20;
int range = 1000;

NumberList list = new NumberList();

for (int i=1; i<=n; i++) {
int x = r.nextInt(range);
list.insertAtHead(x);
System.out.println("" + x + ": " + list);
}
}

public static void testInsertAtTail() {

Random r = new Random();
int n = 20;
int range = 1000;

NumberList list = new NumberList();

for (int i=1; i<=n; i++) {
int x = r.nextInt(range);
list.insertAtTail(x);
System.out.println("" + x + ": " + list);
}
}

public static void testInsertInOrder() {

Random r = new Random();
int n = 20;
int range = 1000;

NumberList list = new NumberList();

for (int i=1; i<=n; i++) {
int x = r.nextInt(range);
list.insertInOrder(x);
System.out.println("" + x + ": " + list);
}
}

public static void main(String[] args) {
//testInsertAtHead();
//testInsertAtTail();
testInsertInOrder();
}
}

Node.java

class Node {

private int number;
private Node next;

public Node(int n) {
this.number = n;
this.next = null;
}
public Node getNext() {
return next;
}
public int getNumber() {
return number;
}
public void setNext(Node n) {
if (n == null)
return;

n.setNext(next);
next = n;
}
public String toString() {
return number + "";
}

}

最佳答案

我认为一旦添加第二个元素,您的 toString() 就会无限循环。您需要将指针移动到下一个节点:

public String toString() {
Node tmp = head;

String result = "";
while (tmp != null) {
result += tmp.toString() + " ";
tmp = tmp.getNext();
}

return result;
}

我还更新了处理 null head 的条件。

关于java - 在java中显示链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35835133/

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