【问题标题】:How to take console input using scanner in Singly / Doubly Linked List in Java (without Collection)?如何在 Java 中的单/双链表中使用扫描仪获取控制台输入(无集合)?
【发布时间】:2017-02-19 13:52:21
【问题描述】:

我想解决一些链表问题,但我无法从控制台获取输入,我不知道我在哪里做错了。

我的代码做错了什么:

import java.util.*;
class ScannerInputLinkedList{
    static class Node{
        int data;
        Node next;
    }
    void insertNode(Node head, int data){
        Node curr = head;

        Node temp = new Node();
        temp.data = data;
        temp.next = null;

        while(curr.next!=null){

            curr = curr.next;
        }
        curr.next = temp;
        System.out.print(curr.data+"->");
    }
    System.out.println();
    public static void main(String[] args) {
        ScannerInputLinkedList obj = new ScannerInputLinkedList();
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        int x;
        Node head = new Node();
        while(t-- > 0){
            x = sc.nextInt();
            obj.insertNode(head, x);

        }
    }

}

【问题讨论】:

  • 我有点困惑,你是否想从用户输入构建一个链表并测试这样的列表?
  • 我想你从来没有分配过obj.head
  • @cricket_007 : 没明白,你能帮忙吗
  • @Crabime : 从用户输入构造一个链表
  • 哦,没关系。大多数链表实现在 List 类中维护一个头节点引用,而不是维护一个带有链接的 Node 元素

标签: java linked-list java.util.scanner singly-linked-list doubly-linked-list


【解决方案1】:

只是您的代码有一个小问题。打印语句(位于 main 方法上方)在任何方法之外。事实上,它根本不需要。只需将其删除并在第 19 行将 System.out.print(...) 更改为 System.out.println(...)。这将使您的代码没有错误。

此解决方案是针对您无法获得输入的问题。除此之外,尚不清楚您要达到的目标。如果您尝试将节点附加到链接列表,则需要重新检查您的逻辑。您的代码正在创建一个已经有一个节点的列表,并附加到它,但您正在打印下一个是新节点的节点的数据。

对于输入 [t = 1, x = 3],您的代码正在打印 0->。这个“0”是输入集的第一个节点的数据,你的新节点将是第二个节点。

无论如何,只是为了解决您无法接受输入的问题,这里是更正的代码。您可以使用诸如 netbeans 或 eclipse 之类的 IDE 来快速识别您的代码有什么问题。

import java.util.*;
class ScannerInputLinkedList{

 static class Node{
    int data;
    Node next;
}
void insertNode(Node head, int data){
    Node curr = head;

    Node temp = new Node();
    temp.data = data;
    temp.next = null;

    while(curr.next!=null){

        curr = curr.next;
    }
    curr.next = temp;
    System.out.println(curr.data+"->");
}
public static void main(String[] args) {
    ScannerInputLinkedList obj = new ScannerInputLinkedList();
    Scanner sc = new Scanner(System.in);
    int t = sc.nextInt();
    int x;
    Node head = new Node();
    while(t-- > 0){
        x = sc.nextInt();
        obj.insertNode(head, x);

    }
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-05
    • 2013-04-13
    • 2017-07-12
    • 2019-12-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    相关资源
    最近更新 更多