从自定义链表打印整数

wj8zmpe1  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(341)

下面是一个样本测试问题,我完全失去了对和没有线索如何回答。
“您将得到一个文本文件,其中包含一系列按升序排列的整数。写一个完整的程序,把文件的内容按相反的顺序打印出来。必须使用链表来保存文件的内容,并且必须定义自己的链表类。不要使用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;
    }
}
i5desfxk

i5desfxk1#

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]);
}
}

相关问题