Site icon TestingDocs.com

Write a simple java program to traverse a single linked list?

Overview

In a single linked list, each node consists of data and a pointer that points to the next node in the list. Below is the visual representation of each node in a single linked list.

 

class Node {

    public int data;
    public Node next;

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

}

 

The data is the actual data for example numbers, strings , objects etc. The next points to the next node in the list. Note that the last node does not point to any node. We must set the next field to null.

Java Program

public class LinkedListExample {

    class Node {

        public int data;
        public Node next;

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

    }

    private Node head;
    private int size;

    private LinkedListExample(){
        head = null;
        size = 0;
    }

    public void addNode(int data){
        Node newNode = new Node(data);
        if(head == null)
            head = newNode;
        else{
            Node last = head;
            while(last.next != null)
                last = last.next;
            last.next = newNode;
        }
        ++size;
    }

    public void printList(){
        if(head == null)
            return;
        Node walkNode = head;
        while(walkNode != null){
            System.out.print( "[" + walkNode.data + "| -> ");
            walkNode = walkNode.next;
        }
        System.out.println("null");

    }

    public void size(){
        System.out.println("Linked List Size is : "+size);
    }

    public boolean isEmpty(){
        return (size == 0);
    }

    public static void main(String[] args){
        LinkedListExample list = new LinkedListExample();

        list.addNode(23);
        list.addNode(77);
        list.addNode(103);
        list.printList();
        list.size();
    }
}

 

Run output of the program

Sample Output

[23| -> [77| -> [103| -> null
Linked List Size is : 3

 

Exit mobile version