How to Calculate Length of LinkedList

How to Calculate Length of LinkedList
SOURCE : LengthLinkedList.java


/**
* @author sandeep
*
*/
public class LengthLinkedList {

// for this use ListNode Class given in this Tutorial
private static int ListLength(ListNode headNode) {

int length = 0;
ListNode CurrentNode = headNode;
System.out.print("LinkedList::::: ");
while (CurrentNode != null) {
System.out.print(CurrentNode.getData()+"->");
length++;
CurrentNode = CurrentNode.getNext();
}
System.out.print("null");
return length;
}

public static void main(String[] args) {
ListNode ls = new ListNode(10);
ListNode ls0 = new ListNode(20);
ListNode ls1 = new ListNode(30);
ListNode ls2 = new ListNode(40);
ListNode ls3 = new ListNode(50);
ls.setNext(ls0);
ls0.setNext(ls1);
ls1.setNext(ls2);
ls2.setNext(ls3);

// length of linked List
System.out.println(" Length of LinkedList before Inserstion::: " + ListLength(ls));

}

}


INPUT

LinkedList::::: 10->20->30->40->50->null



OUTPUT

Length of LinkedList before Inserstion::: 5







Sandeep Kumar D

Hi, I have written and developed this post so that most of people will be benefited. I'm committed to provide easy and in-depth tutorials on various technologies.I hope it will help you a lot.

- Sandeep Kumar D

Follow Me @Google+




SHARE

    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment