Given LinkedList is Circular LinkedList or Not using Floyd Algorithm

Given LinkedList is Circular LinkedList or Not using Floyd Algorithm
SOURCE : CircularLinkedList.java


/**
*
*/
package LinkedList;

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

/**
* @param args
*/
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);
ListNode ls4 = new ListNode(60);
ListNode ls5 = new ListNode(70);
ListNode ls6 = new ListNode(80);
ls.setNext(ls0);
ls0.setNext(ls1);
ls1.setNext(ls2);
ls2.setNext(ls3);
ls3.setNext(ls4);
ls4.setNext(ls5);
ls5.setNext(ls6);
ls6.setNext(ls2);

System.out.println("Given LinkedList is Circular ::: "
+ isCircularList(ls));

}

private static boolean isCircularList(ListNode ls) {

if (ls == null || ls.getNext() == null)
return false;

ListNode slowPtr = ls;
ListNode fastPtr = ls.getNext().getNext();
while (slowPtr != null || fastPtr != null) {

if (fastPtr != null)
if (slowPtr == fastPtr)
return true;

slowPtr = slowPtr.getNext();
if (slowPtr == fastPtr)
return true;

fastPtr = fastPtr.getNext().getNext();
if (fastPtr != null)
if (slowPtr == fastPtr)
return true;

}
return false;

}

}


INPUT





OUTPUT

Given LinkedList is Circular ::: true






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