简体   繁体   中英

Why can I not print the last element in my linkedlist

I have implemented a basic linkedlist, that contains a Node class and a Linkedlist class, the Node class is a java generic.

I am just wondering, why does my last element not print, when I do a print statement here is my classes

Linkedlist.class

  /**
 * A linked list is a sequential list of nodes that hold data that point to nodes also containng data
 *
 * Linked lists are used in Lists, Queues and Stacks
 * Great for creating circular lists
 *
 * Head = first node in a linkedlist
 * Tail = last node in a linkedlist
 * Pointer = reference to the next node in a linkedlist.
 * Node = object containing data.
 */
public class Linkedlist<T> {
    Node Head;

    public Linkedlist(Node n)
    {
        Head = n;
    }

    public boolean contains(T obj)
    {

        Node n = Head;
        while (!(n.getNextNode().equals(null))){
            System.out.println(n.getNextNode());  //Last element does not print here
            n = n.getNextNode();
        }
        return false;
    }


}

Node.class

 public class Node<T> {

    Node next = null;
    T data;


    public Node(T data){
        this.data = data;
    };

    public void setNext(Node n)
    {
        next = n;
    }

    public Node getNextNode()
    {
        return this.next;
    }

    public T getData()
    {return this.data;}

    public void printNode()
    {
        System.out.println(getData());
    }

}

Thank you for the assistance, I am using the contains method to check if my while loop is iterating over all the elements. ( I think it, but it is just stopping at the last element and not going any further).

Any help will be appreciated

You have to rethink how you print the data. Currently you never print the data from Head node, as you only ever print the next node ( n.getNextNode() ). You are also breaking the loop when the next element is null. This causes the last element to not be printed, as getNextNode() will return null before the print call.

Instead go like this:

public boolean contains(T obj) {
    Node n = Head;
    do {
        System.out.println(n.getData()); // print data of current node
        n = n.getNextNode(); // move to next node
    } while (n != null); // break if we are behind next node. n is null
    return false;
}

or if you might have an empty list (node passed into constructor is null):

public boolean contains(T obj) {
    Node n = Head;
    while (n != null) {
        System.out.println(n.getData());
        n = n.getNextNode();
    }
    return false;
}

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