简体   繁体   中英

Java: Linked list node isn't working in my code

So I am very very at linked list and creating nodes is very confusing. for my program, I have to create a method in main class called insertAfter(TrackerNode nodeLoc) that refers to another class I have created for inserting data in node. The user inputs are initially, a total number of nodes, then data for each node (name and age).

There are a few issues with your code as posted, the age field (according to your requested output) should be an int and you need to remember which order you declare age and name in your constructors. It is also possible to shorten the repetitive constructors with this() ; and I would prefer using toString() over a custom data dumper method. Like,

public class TrackerNode {
    private int age;
    private String name;
    private TrackerNode nextNodeRef; // Reference to the next node

    public TrackerNode() {
        this("", 0);
    }

    public TrackerNode(String name, int age) {
        this(name, age, null);
    }

    public TrackerNode(String name, int age, TrackerNode nextLoc) {
        this.age = age;
        this.name = name;
        this.nextNodeRef = nextLoc;
    }

    public void insertAfter(TrackerNode nodeLoc) {
        TrackerNode tmpNext = this.nextNodeRef;
        this.nextNodeRef = nodeLoc;
        nodeLoc.nextNodeRef = tmpNext;
    }

    // Get location pointed by nextNodeRef
    public TrackerNode getNext() {
        return this.nextNodeRef;
    }

    @Override
    public String toString() {
        return String.format("%s, %d", this.name, this.age);
    }
}

Then your main loop should actually use the i you read and you need to reset to the head node before you print. Something like,

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);

    // References for TrackerNode objects
    TrackerNode headNode = null, currNode = null, lastNode = null;

    // Scan the number of nodes
    int i = scnr.nextInt();

    // in data and insert into the linked list
    for (int k = 0; k < i; k++) {
        String name = scnr.next();
        int age = scnr.nextInt();
        scnr.nextLine();
        if (lastNode != null) {
            currNode = new TrackerNode(name, age);
            lastNode.insertAfter(currNode);
        } else {
            currNode = headNode = new TrackerNode(name, age);
        }
        lastNode = currNode;
    }

    // Print linked list
    currNode = headNode;
    while (currNode != null) {
        System.out.println(currNode);
        currNode = currNode.getNext();
    }
}

Which I tested with your provided input (and the output I received seems to match the posted expectations):

3
John
22
Silver
24
Smith
21
John, 22
Silver, 24
Smith, 21

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