简体   繁体   中英

Printing Integers from Self Defined Linked List

Below is a sample test question that I am completely lost on and have no clue how to answer.

"You are given a text file containing a series of integers in ascending order. Write a complete program to print the contents of the file out in reverse order. You must use a linked list to hold the contents of the file, and you must define your own linked list classes. Do not use the Java API LinkedList implementations."

My Question Is:

I have the following (working) code, but does this definition fill the requirements for the above question? And if yes, how would I use it to print integers. If No, what do I have to add replace to make it work?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM