Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
}
like image 902
Shawn Avatar asked Oct 09 '13 21:10

Shawn


People also ask

How do I toString a linked list?

For converting a linked list to a string we need to traverse the linked list and after that, we need to append the element of the linked list to the string variable. We can use String class, StringBuilder, or StringBuffer for converting a LinkedList to string.

How do I print a linked list?

PrintElement.java Given a pointer to the head node of a linked list, print its elements in order, one element per line. If the head pointer is null (indicating the list is empty), don't print anything. The void Print(Node* head) method takes the head node of a linked list as a parameter.

What is to toString () method for?

The toString() method can be used to convert a string object into a string.


3 Answers

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() {
            String result = "";
            LinkedListNode current = head;
            while(current.getNext() != null){
                result += current.getData();
                if(current.getNext() != null){
                     result += ", ";
                }
                current = current.getNext();
            }
            return "List: " + result;
}
like image 132
Marin Avatar answered Oct 18 '22 20:10

Marin


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();
    }

}
like image 43
TwentyMiles Avatar answered Oct 18 '22 19:10

TwentyMiles


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());
}
like image 20
zaerymoghaddam Avatar answered Oct 18 '22 19:10

zaerymoghaddam