package linkedlist.singly; public class DetectLoopInLinkList { Node startNode; public static void main(String[] args) { DetectLoopInLinkList g = new DetectLoopInLinkList(); Node n1 = new Node(10); Node n2 = new Node(20); Node n3 = new Node(30); Node n4 = new Node(40); Node n5 = new Node(50); Node n6 = new Node(60); Node n7 = new Node(70); Node n8 = new Node(80); g.startNode = n1; n1.setNext(n2); n2.setNext(n3); n3.setNext(n4); n4.setNext(n5); n5.setNext(n6); n6.setNext(n7); n7.setNext(n8); n8.setNext(n4); System.out.println(g.isLoopPresent()); } private boolean isLoopPresent(){ Node str1=startNode, str2=startNode; while(str2!=null && str2.getNext()!=null){ str1 = str1.getNext(); str2 = str2.getNext().getNext(); if(str1==str2)return true; } return false; } }
Questions on Stack, Queues, Linkedlist, Binary Trees, Sorting, Searching, Graphs etc with solution using Java Language.
Saturday, 23 May 2015
Detect if there is Loop present in a Linkedlist
Labels:
Linkedlist
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment