-
Notifications
You must be signed in to change notification settings - Fork 0
/
countnodes2.java
51 lines (45 loc) · 1009 Bytes
/
countnodes2.java
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
//counting nodes of a linked list by recursive approach
class Node
{
int data;
Node next;
Node(int d)
{
data=d;
next=null;
}
}
public class Recurnodes
{
Node head;
public void insert(int element)
{
Node n = new Node(element);
n.next = head;
head=n;
}
//using recursion
public int count(Node no)
{
if(no==null)
return 0;
return(1+count(no.next));
}
//this is simply a wrapper class over the recursive count class
public int wrappercount()
{
return(count(head)); //this passes head to the count function
}
public static void main(String args[])
{
Recurnodes rn = new Recurnodes();
rn.insert(65);
rn.insert(43);
rn.insert(56);
rn.insert(87);
rn.insert(98);
rn.insert(9);
rn.insert(78);
System.out.println("The number of nodes is : "+rn.wrappercount());
}
}