In this post, We will learn How to find the length of a Singly Linked List in Java?
Program Logic:
- Initialize int length = 0, if List is Empty then return length.
- Traverse Linked List from head to last node(remember the last node always point to null) and increment length by 1 in every iteration finally return length.
Below is the complete source code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
package com.kkjavatutorials.util; /** * How to find length/size of a Singly Linked List in Java ? * @author KK JavaTutorials */ public class LinkedList<T> { private Node<T> head; //This internal class represents Node in Linked List private static class Node<T>{ private T data; private Node<T> next; public Node(T data) { super(); this.data = data; this.next = null; } } /** * This method returns size/length of Linked List * @return size of Linked List */ public int size() { int length = 0; if(head == null) { return length; } Node<T> currentNode = head; while (currentNode != null) { length ++; currentNode = currentNode.next; } return length; } /** * This method insert Node in Linked List * @param data has to insert in the List */ public void insert(T data) { Node<T> newNode = new Node<T>(data); if(head == null) { head = newNode; }else { Node<T> currentNode = head; while (currentNode.next != null) { currentNode = currentNode.next; } currentNode.next = newNode; } } /** * Method which traverse Linked List and display all data. */ public void displayLinkedList() { Node<T> currentNode = head; while(currentNode!= null) { System.out.print(currentNode.data+"->"); currentNode = currentNode.next; } System.out.println(currentNode); } public static void main(String[] args) { LinkedList<Integer> linkedList = new LinkedList<>(); linkedList.insert(5); linkedList.insert(10); linkedList.insert(15); linkedList.insert(20); linkedList.insert(25); System.out.println("Linked List is:"); linkedList.displayLinkedList(); System.out.println("Size of Linked List is :"+linkedList.size()); } } |
Output of this Program:
Linked List is:
5->10->15->20->25->null
Size of Linked List is :4
You May Also Like:
- How to search an element in a Singly Linked List in Java ?
- How to find middle node in a Singly Linked List in Java ?
- How to Insert node at the end of a Singly Linked List in Java ?
- How to insert a node at the beginning of a Singly Linked List in Java?
- Representation of Singly Linked List in Java ?
- How to check whether a linked list has a loop/cycle in java ?
- Queue Implementation using LinkedList in java
- Queue Implementation using an array in java
That’s all about the How to find the length of a Singly Linked List in Java?
If you have any feedback or suggestion please feel free to drop in below comment box.