【问题标题】:How can I use toString() to pring a linked list of integers in Java?如何使用 toString() 在 Java 中打印整数链表?
【发布时间】:2021-09-24 16:26:01
【问题描述】:

我目前正在创建一个程序来使用 toString() 方法打印随机整数的链接列表。但是,事实上,我的程序没有错误,但不会打印任何内容。我有一种感觉,错误可能与 toString() 中的 val != null 语句有关,但我对 toString() 和链表非常陌生,所以我不能确定。为什么我的程序不打印链表?

import java.util.Random;
import java.util.*;
public class IntList {
    private class Node {
        int value;
        Node next;
    }
    private Node head;

    public IntList(int n) {
        LinkedList<Integer> list = new LinkedList<Integer>();
        Random rand = new Random();
        for (int i = 0; i < n; i++) {
            list.add(rand.nextInt(n));
        }
    }

    public String toString() {
        String result = "";
        for(IntList.Node val = head; val != null; val = val.next) {
            result += val.value;
        }
        return result;
    }

    public static void main(String[] args) {
        IntList list = new IntList(6);
        System.out.println(list);
    }
}

如果错误在其他地方而不是在 toString() 中,请告诉我,我会尽力找到它!

【问题讨论】:

    标签: java list tostring


    【解决方案1】:

    您不会在构造函数中将节点添加到 IntList。你的 head 用 null 初始化,所以没有什么要打印的。

    用这样的东西扩展你的构造函数。

    public IntList(int n) {
            LinkedList<Integer> list = new LinkedList<Integer>();
            Random rand = new Random();
            for (int i = 0; i < n; i++) {
                list.add(rand.nextInt(n));
            }
            //Init head
            this.head = new Node(list.get(0),null); //Add constructor to the Node
            // Append all the elements from the list.
            for(int i : list){
            Node lastNode = head;
            while(lastNode.getNext() != null){ 
               lastNode = lastNode.getNext(); 
            }
            lastNode.setNext( new Node(i,null));
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多