एक लिंक्डलिस्ट में लूप का पता लगाने के लिए जावा प्रोग्राम

इस उदाहरण में, हम यह पता लगाना सीखेंगे कि Java में LinkedList में लूप है या नहीं।

इस उदाहरण को समझने के लिए, आपको निम्नलिखित जावा प्रोग्रामिंग विषयों का ज्ञान होना चाहिए:

  • जावा लिंक्डलिस्ट
  • जावा के तरीके

उदाहरण: एक लिंक्डलिस्ट में लूप का पता लगाएं

 class LinkedList ( // create an object of Node class // represent the head of the linked list Node head; // static inner class static class Node ( int value; // connect each node to next node Node next; Node(int d) ( value = d; next = null; ) ) // check if loop is present public boolean checkLoop() ( // create two references at start of LinkedList Node first = head; Node second = head; while(first != null && first.next !=null) ( // move first reference by 2 nodes first = first.next.next; // move second reference by 1 node second = second.next; // if two references meet // then there is a loop if(first == second) ( return true; ) ) return false; ) public static void main(String() args) ( // create an object of LinkedList LinkedList linkedList = new LinkedList(); // assign values to each linked list node linkedList.head = new Node(1); Node second = new Node(2); Node third = new Node(3); Node fourth = new Node(4); // connect each node of linked list to next node linkedList.head.next = second; second.next = third; third.next = fourth; // make loop in LinkedList fourth.next = second; // printing node-value System.out.print("LinkedList: "); int i = 1; while (i <= 4) ( System.out.print(linkedList.head.value + " "); linkedList.head = linkedList.head.next; i++; ) // call method to check loop boolean loop = linkedList.checkLoop(); if(loop) ( System.out.println("There is a loop in LinkedList."); ) else ( System.out.println("There is no loop in LinkedList."); ) ) )

आउटपुट

 लिंक्डलिस्ट: 1 2 3 4 लिंक्डलिस्ट में एक लूप है।

उपरोक्त उदाहरण में, हमने जावा में एक लिंक्डलिस्ट लागू किया है। लिंक्डलिस्ट में एक लूप है या नहीं, यह जांचने के लिए हमने फ्लोयड के साइकल फाइंडिंग एल्गोरिदम का इस्तेमाल किया है ।

checkLoop()विधि के अंदर कोड को नोटिस करें । यहां, हमारे पास पहले और दूसरे नाम के दो चर हैं जो नोड्स को पीछे छोड़ते हैं LinkedList

  • पहला - एकल पुनरावृत्ति पर 2 नोड्स के साथ पार
  • दूसरा - एकल पुनरावृत्ति पर 1 नोड के साथ पार

दो नोड्स अलग-अलग गति से चल रहे हैं। इसलिए, यदि कोई लूप इन है तो वे मिलेंगे LinkedList

दिलचस्प लेख...