• Register
Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Counting all the nodes in a Linked List

0 votes
297 views
Find length of linked list java
    Or
Count all nodes in a Linked List
asked Sep 12, 2017 in Data Structure And Algorithm by Biswajit Pan

1 Answer

0 votes
See the following running example to get length or size of the linked list:-

package com.ds.linkedlist;

public class Node<T> {

    private T data;
    private Node<T> next;
   
    public Node(){
        setData(null);
        setNext(null);
    }
   
    public Node(T data){
        setData(data);
        setNext(null);
    }
   
    public T getData(){
        return data;
    }
   
    public void setData(T data){
        this.data = data;
    }
   
    public Node<T> getNext(){
        return next;
    }
   
    public void setNext(Node<T> next){
        this.next = next;
    }
   
}

package com.ds.linkedlist;

import java.util.HashMap;

public class SingleLinkedList<T> {
    Node<T> head = null;
    //
    public int getNodeLength(){
        Node<T> tempNode = head;
        if(tempNode==null){
            return 0;
        }
        int count=0;
        while(tempNode != null){
            count++;
            tempNode = tempNode.getNext();
        }
        return count;
    }

    public void addFirst(T data){
        if(data == null){
            return;
        }
        if(head == null){
            head = new Node<T>(data);
        }else{
            Node<T> newNode = new Node<T>(data);
            newNode.setNext(head);
            head = newNode;
        }
    }
   
    public void getNodeData(){
        Node<T> tempNode = head;
        if(tempNode==null){
            return;
        }
        while(tempNode != null){
            System.out.print(tempNode.getData()+" ");
            tempNode = tempNode.getNext();
        }
    }
}

package com.ds.linkedlist;

public class LinkedListTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        SingleLinkedList<Integer> singleLinkedList = new SingleLinkedList<Integer>();
        singleLinkedList.addFirst(10);
        singleLinkedList.addFirst(20);
        singleLinkedList.addFirst(30);
        singleLinkedList.addFirst(30);
        singleLinkedList.addFirst(40);
        System.out.println("Node List:-");
        singleLinkedList.getNodeData();
        System.out.println("\nFirst List Length: "+singleLinkedList.getNodeLength());
    }
}

Output:-
Node List:-
40 30 30 20 10
Linked List Length: 5
answered Sep 15, 2017 by me_vinod12 (1,960 points)
...