从自定义链表打印整数



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

"您将得到一个文本文件,其中包含一系列按升序排列的整数。编写一个完整的程序,以相反的顺序打印出文件的内容。必须使用链接列表来保存文件的内容,并且必须定义自己的链接列表类。不要使用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;
}
}
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]);
}
}
}

最新更新