Find length of a Singly Linked List
We will see how to Find the length of a Singly Linked List.
Firstly, define a Node name current and assign the head to the current because we will not change the head reference.
Secondly, we need to visit each node one by one and increment the count value if the current next points to the null which means there is no node left to be visited.
Finally, terminate the while loop and return the count value.
public int findLength() {
int count = 0;
Node current = head;
while(current !=null) {
count++;
current = current.next;
}
return count;
}
Java 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 | /*Node of a single linked list of integer */ public class SinglyLinkedList { private static Node head; /* instance variable */ private static class Node { private int data; /* we assume data integer */ private Node next; /* Create a node with the given data and next node */ public Node(int data) { this.data = data; this.next = null; } } public int findLength() { if(head==null){ return 0; } int count = 0; Node current = head; while(current !=null) { count++; current = current.next; } return count; } public static void main(String[] args) { SinglyLinkedList s = new SinglyLinkedList(); s.head = new Node(10); Node second = new Node(7); Node third = new Node(20); Node fourth = new Node(8); s.head.next = second; // 10 --> 7 second.next = third; // 10 -->7 -->20 third.next = fourth; // 10 -->7 --> 20 -->8 -->null System.out.println("Singly Linked List Length: "+s.findLength()); } } |
Output
Singly Linked List Length: 4
You may also like...Singly Linked ListsInsert node at the beginning of a Singly Linked List Insert a Node at a Specific Position in a Linked List |