Java Linked List Length Recursive Solution
Chapter:
Interview Programs
Last Updated:
17-11-2016 14:42:51 UTC
Program:
/* ............... START ............... */
/* Linked list Node*/
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
public class JavaLinkedListLengthRecursiveSolution {
Node head; // head of list
public void push(int new_data) {
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
public int getCountRec(Node node) {
// Base case
if (node == null)
return 0;
return 1 + getCountRec(node.next);
}
public int getCount() {
return getCountRec(head);
}
public static void main(String[] args) {
JavaLinkedListLengthRecursiveSolution llist =
new JavaLinkedListLengthRecursiveSolution();
llist.push(1);
llist.push(3);
llist.push(1);
llist.push(2);
llist.push(1);
System.out.println("Count of nodes is " + llist.getCount());
}
}
/* ............... END ............... */
Output
Tags
Linked List Length Recursive Solution , Java, Interview Programs