[java] Printing out a linked list using toString

Ok guys, so I am trying to learn how to print out a linked list. I have all the methods that I would need to use for the list, but I can't figure out how to display the values of the nodes. Right now there is nothing in my main method because I kept getting errors trying to call non static methods in the main. I have a toString method that displays the contents of the list. How would I go about calling this toString to display the value of each node? Any advice will be greatly appreciated.

Here is the node class:

public class LinkedListNode
{

    private int data;
    private LinkedListNode next;


    public LinkedListNode(int data)
    {
        this.data = data;
        this.next = null;
    }

    public int getData()
    {
        return data;
    }

    public void setData(int d)
    {
        data = d;
    }

    public LinkedListNode getNext()
    {
        return next;
    }

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

Here is the LinkedList class that contains the main and methods to manipulate the list:

public class LinkedList {

    public LinkedListNode head;

    public static void main(String[] args) {

    LinkedList l = new LinkedList();
    l.insertFront(0);
    System.out.println(l.toString());

    }

    public LinkedList() {
        this.head = null;
    }

    public int removeFront(){
        if(head == null){
            System.out.println("Error - Attempting to call removeFront() on empty list");
            return 0;
        }else{
            int temp = head.getData();
            head = head.getNext();  
            return temp;
        }

    }

    public void insertFront(int data){
        if(head == null){
            head = new LinkedListNode(data);
        }else{
            LinkedListNode newNode = new LinkedListNode(data);
            newNode.setNext(head);
            head = newNode;
        }       
    }

    public void insertBack(int data){
        if(head == null){
            head = new LinkedListNode(data);
        }else{
            LinkedListNode newNode = new LinkedListNode(data);
            LinkedListNode current = head;
            while(current.getNext() != null){
                current = current.getNext();
            }
            current.setNext(newNode);
        }       
    }

    public int removeBack(){
        if(head == null){
            System.out.println("Error - Attempting to call removeBack() on empty list");
            return 0;
        }else if (head.getNext() == null){
            int temp = head.getData();
            head = null;
            return temp;
        }else{

            LinkedListNode current = head;
            while(current.getNext().getNext() != null){
                current = current.getNext();
            }
            int temp = current.getNext().getData();
            current.setNext(null);
            return temp;
        }       
    }

    public String toString(){
        String retStr = "Contents:\n";

        LinkedListNode current = head;
        while(current != null){
            retStr += current.getData() + "\n";
            current = current.getNext();

        }

        return retStr;
    }

    public LinkedListNode getHead() {
        return head;
    }

    public void setHead(LinkedListNode head) {
        this.head = head;
    }
}

This question is related to java linked-list tostring pretty-print

The answer is


As has been pointed out in some other answers and comments, what you are missing here is a call to the JVM System class to print out the string generated by your toString() method.

LinkedList myLinkedList = new LinkedList();
System.out.println(myLinkedList.toString());

This will get the job done, but I wouldn't recommend doing it that way. If we take a look at the javadocs for the Object class, we find this description for toString():

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The emphasis added there is my own. You are creating a string that contains the entire state of the linked list, which somebody using your class is probably not expecting. I would recommend the following changes:

  1. Add a toString() method to your LinkedListNode class.
  2. Update the toString() method in your LinkedList class to be more concise.
  3. Add a new method called printList() to your LinkedList class that does what you are currently expecting toString() to do.

In LinkedListNode:

public String toString(){
   return "LinkedListNode with data: " + getData();
}

In LinkedList:

public int size(){
    int currentSize = 0;
    LinkedListNode current = head;
    while(current != null){
        currentSize = currentSize + 1;
        current = current.getNext();
    }

    return currentSize;
}

public String toString(){
    return "LinkedList with " + size() + "elements.";
}

public void printList(){
    System.out.println("Contents of " + toString());

    LinkedListNode current = head;
    while(current != null){
        System.out.println(current.toString());
        current = current.getNext();
    }

}

I do it the following way:

public static void main(String[] args) {

    LinkedList list = new LinkedList();
    list.insertFront(1);
    list.insertFront(2);
    list.insertFront(3);
    System.out.println(list.toString());
}

String toString() {
    StringBuilder result = new StringBuilder();
    for(Object item:this) {
        result.append(item.toString());
        result.append("\n"); //optional
    }
    return result.toString();
}

When the JVM tries to run your application, it calls your main method statically; something like this:

LinkedList.main();

That means there is no instance of your LinkedList class. In order to call your toString() method, you can create a new instance of your LinkedList class.

So the body of your main method should be like this:

public static void main(String[] args){
    // creating an instance of LinkedList class
    LinkedList ll = new LinkedList();

    // adding some data to the list
    ll.insertFront(1);
    ll.insertFront(2);
    ll.insertFront(3);
    ll.insertBack(4);

    System.out.println(ll.toString());
}

A very simple solution is to override the toString() method in the Node. Then, you can call print by passing LinkedList's head. You don't need to implement any kind of loop.

Code:

public class LinkedListNode {
    ...

    //New
    @Override
    public String toString() {
        return String.format("Node(%d, next = %s)", data, next);
    }
} 


public class LinkedList {

    public static void main(String[] args) {

        LinkedList l = new LinkedList();
        l.insertFront(0);
        l.insertFront(1);
        l.insertFront(2);
        l.insertFront(3);

        //New
        System.out.println(l.head);
    }
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to linked-list

Creating a node class in Java Simple linked list in C++ Insert node at a certain position in a linked list C++ Printing out a linked list using toString How to work with string fields in a C struct? JTable - Selected Row click event When to use HashMap over LinkedList or ArrayList and vice-versa C: How to free nodes in the linked list? Java how to sort a Linked List? C linked list inserting node at the end

Examples related to tostring

How do I print my Java object without getting "SomeType@2f92e0f4"? What is the meaning of ToString("X2")? Printing out a linked list using toString ToString() function in Go to_string is not a member of std, says g++ (mingw) Confused about __str__ on list in Python How to convert an int array to String with toString method in Java Override valueof() and toString() in Java enum Checking session if empty or not Converting an object to a string

Examples related to pretty-print

Print a list of space-separated elements in Python 3 Printing out a linked list using toString How can I pretty-print JSON using Go? JSON.stringify output to div in pretty print way Convert JSON String to Pretty Print JSON output using Jackson How to prettyprint a JSON file? Pretty-print a Map in Java Pretty-Print JSON Data to a File using Python How do I pretty-print existing JSON data with Java? Pretty-Printing JSON with PHP