hello, i am new to link list in java, the output() method isn't displaying the last value entered by the user, can i get some help? also you will see some commented methods that i still need to create, if would be of much help, if you can get me started on them as well, but for now i need help with the output

import java.util.*;

public class Node{
    int num;
    Node next;

    public Node (int n){
        num = n;
public class JavaApplication3 { 
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Node top, np, last = null; // initialise nodes
        top = null;

        System.out.printf("Enter some interger ending with 0\n");
        int n; 
        n = in.nextInt();
        while (n!=0){            
            np = new Node(n);
            if (top==null) 
                top = np;
                last.next = np;            
            last = np;           
            n = in.nextInt();
            //end while


        //get(index);//return the Indext element of the list
        //index0f(x);//return the index of the first occurrence of  x in the list, return -1 if x is not in the list
        //remove(Index);//remove and return the indexth element, elements with higher index  have their index reduced by 1
        //add(theIndex, x);//insert x as the indexth element, elements with theIndex >= index have their index increased by 1
       output(top);//output the list elements from left to right
    }  //end main
    public static void output(Node top){
        while(top.next != null){
            System.out.printf("%d\n", top.num);
            top = top.next;
1 Year
Discussion Span
Last Post by JamesCherrill

It's skipping the last item because, for the last item in the list, top.next == null. Therefore the final print loop isn't actioned.
You'll need another way of determining when you're at the end of the list, using an index or moving onto the next item and checking if it is null (rather than it's next sibling).


Hericles has the right analysis, but the solution is simpler than he suggests.
Here's a hint that should get you thinking in the right direction:
What happens when you call this method passing an empty list (ie top == null)? Can you fix both problems by just deleting one small thing from your code?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.