Java Linked List Length Iterative Solution
Chapter:
Interview Programs
Last Updated:
17-11-2016 14:36:23 UTC
Program:
/* ............... START ............... */
/* Linked list Node*/
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
public class JavaLinkedListLengthIterativeSolution {
Node head; // head of list
/* Inserts a new Node at front of the list. */
public void push(int new_data) {
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
/* Returns count of nodes in linked list */
public int getCount() {
Node temp = head;
int count = 0;
while (temp != null) {
count++;
temp = temp.next;
}
return count;
}
public static void main(String[] args) {
/* Start with the empty list */
JavaLinkedListLengthIterativeSolution llist =
new JavaLinkedListLengthIterativeSolution();
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 Iterative Solution , Java, Interview Programs