【问题标题】:Printing Integers from Self Defined Linked List从自定义链表打印整数
【发布时间】:2020-11-26 20:09:37
【问题描述】:

下面是一个示例测试问题,我完全迷失了,不知道如何回答。

“给你一个文本文件,其中包含一系列按升序排列的整数。编写一个完整的程序,将文件的内容以相反的顺序打印出来。你必须使用链表来保存文件的内容,并且您必须定义自己的链表类。不要使用 Java API LinkedList 实现。"

我的问题是:

我有以下(工作)代码,但这个定义是否满足上述问题的要求?如果是的话,我将如何使用它来打印整数。如果否,我必须添加什么替换才能使其工作?

public class Node {
    String value;
    Node next;

    public Node(String s) {
        this.value = s;
        next = null;
    }

    public Node(String s, Node n) {
        this.value = s;
        this.next = n;
    }

    public void setValue(String newValue) { //setters
        this.value = newValue;
    }
    public void setNext(Node newNext) {
        this.next = newNext;
    }

    public String getValue() { // getters
        return this.value;
    }
    public Node getNext() {
        return this.next;
    }
}

【问题讨论】:

  • 嗯,它不打印任何东西,不读取文件,也不实现链表,所以它没有完成任务,但它可能可以用作它的一部分。

标签: java linked-list singly-linked-list


【解决方案1】:
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;

class Main {

    public static void main(String args[]) throws Exception {
        LinkedList ll = new LinkedList();
        Scanner sc = new Scanner(new File("yourFile.txt"));
        int i = 0;
        while (sc.hasNextInt()) {
            ll.drive(sc.nextInt());
            i++;// Number of integers
        }
        ll.printing(i);
    }
}

class LinkedList {

    static int arr[];
    Node head;
    static Node ahead = null;// This node has all the nodes merged(see drive() function) forming a linked list.
    
    static class Node {

        int data;
        Node next;
    }

    static Node newNode(int data) {
        Node nn = new Node();
        nn.data = data;
        nn.next = null;
        return nn;
    }

    static Node insertEnd(Node head, int data) {
        if (head == null) {
            return newNode(data);
        } else {
            head.next = insertEnd(head.next, data);
        }
        return head;
    }

    public static void drive(int arg) {
        ahead = insertEnd(ahead, arg);
    }

    static void printing(int i) {
        if (ahead == null) {
            return;
        }
        //Storing in reverse
        arr = new int[i];

        for (int j = i - 1; j >= 0; j--, ahead = ahead.next) {
            arr[j] = ahead.data;
        }

        //Printing in reverse
        for (int j = 0; j < i; j++) {
            System.out.println(arr[j]);
        }
    }
}

【讨论】:

  • 非常感谢,我就是想问一下驱动方法的目的是什么?
  • 驱动函数从主函数(while循环)中连续调用每个整数。驱动函数用于不断向使用'insertEnd'方法的现有节点添加新节点。因此,当传递参数时'ahead'始终为空时,每次添加一个新节点为head==null。所以这里 'insertEnd' 最多只能执行一次递归,创建一个合适的链表。
猜你喜欢
  • 2018-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-25
  • 1970-01-01
相关资源
最近更新 更多