Tan
Tan

Reputation: 1575

How can I display all the contents of the LinkedList?

Please consider the following code for linkedlist. Basically I've created three nodes in the LinkedList class and trying to display the contents but I'm doing something wrong in the DisplayLinkedList() method. Right now I'm getting my output as follows :

B
C
null

I wanna display it as follows: A B C

respectively. Could anyone tell me where I'm wrong in the DisplayLinkedList() method ?

package MyPackage;


class Node {

String data;
Node next;

public Node(String data, Node next){

    this.data = data;
    this.next = next;

}

public String getData(){
    return data;
}

public Node getNext(){

    return next;
}

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

 public String toString() {
     return this.data;
 }


}

// CREATING LINKED LIST BACKWARDS AND APPLYING SOME OPERATIONS ON IT


class LinkedList{

Node cNode = new Node("C", null);

Node bNode = new Node("B", cNode);

Node list = new Node("A", bNode);


public void DisplayLinkedList(){

    Node prev = null;
    Node curr = list;

    while(curr != null){

        prev = curr;
        curr = curr.getNext();
        System.out.println(curr);

    }


}




public class LinkedListByME {


public static void main(String[] args) {


    LinkedList ll = new LinkedList();
    ll.DisplayLinkedList();



}

}

Upvotes: 1

Views: 21509

Answers (3)

Tech Nerd
Tech Nerd

Reputation: 832

public void listTrasverse() {
    if(isEmpty()) {
        System.out.print("\nLIST IS EMPTY !!!");
    } else {
        while(current!=null) {
            current.displayLink();
            current=current.next;
        }
    }
}

Use this code to call the displayLink() method in you node class the displayLink() method will be

public void displayLink(){
    System.out.print("\nDATA= "+data);
}

Upvotes: 0

user1599559
user1599559

Reputation:

Your issue is in your loop in DisplayLinkedList. You "miss" the first node because you advance to the next node before printing it.

It should be:

while(curr != null) {
   System.out.println(curr);
   prev = curr;
   curr = curr.getNext();    
}

Also, it looks like you are keeping track of prev without using it. The simplified version of the method could be:

public void DisplayLinkedList() {
    Node curr = list;
    while(curr != null) {
        System.out.println(curr);
        curr = curr.getNext();
    }
}

Upvotes: 5

Scott Woodward
Scott Woodward

Reputation: 325

You're checking if the curr is null, and THEN incrementing, which makes curr a null value that you try to print.

while(curr != null){
    prev = curr;
    curr = curr.getNext();
    System.out.println(curr);

}

doing the print first should help.

while(curr != null){
    System.out.println(curr);
    prev = curr;
    curr = curr.getNext();
}

Upvotes: 5

Related Questions