Hello! So I’m doing a 30 day coding challenge where I solve a few questions every day and thought of posting them here on my blog so that you guys can join the challenge too!
Welcome to Coding challenge Day 22: Problem 1! Be sure to post your answers, queries etc in the comments!
Problem: Find length of linked list (Recursive)
Sample: Linked List: 1—>2—>3
Output:
1 2 3
Length of linked list: 3
Solution:
package linkedlist;
//length of linked list (recursive)
public class Program011length_of_linked_list_Recursive {
Node head;
static class Node{
int data;
Node next;
Node(int d)
{
data=d;
next=null;
}
}
public int find_length(Node node)
{
if(node==null)
return 0;
else
return 1+find_length(node.next);
}
public void printlist()
{
Node n=head;
while(n!=null)
{
System.out.print(n.data+ " ");
n=n.next;
}
System.out.println();
}
public static void main (String [] args)
{
Program011length_of_linked_list_Recursive llist= new Program011length_of_linked_list_Recursive();
llist.head= new Node(1);
Node second= new Node(2);
Node third= new Node(3);
llist.head.next=second;
second.next=third;
llist.printlist();
System.out.println("Length of linked list: "+ llist.find_length(llist.head));
}
}
Happy Learning!!