Java programma, lai noteiktu cilpu LinkedList

Šajā piemērā mēs iemācīsimies noteikt, vai Java ir LinkedList cilpa.

Lai saprastu šo piemēru, jums jāpārzina šādas Java programmēšanas tēmas:

  • Java LinkedList
  • Java metodes

Piemērs: Atrodiet cilpu 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."); ) ) )

Rezultāts

 LinkedList: 1 2 3 4 LinkedList ir cilpa.

Iepriekš minētajā piemērā mēs esam ieviesuši LinkedList Java. Mēs esam izmantojuši Floida cikla atrašanas algoritmu, lai pārbaudītu, vai LinkedList ir cilpa.

Ievērojiet kodu checkLoop()metodes iekšpusē . Šeit mums ir divi mainīgie, kuru nosaukums ir pirmais un otrais, kas šķērso mezglus LinkedList.

  • pirmais - šķērso 2 mezglus vienā atkārtojumā
  • otrais - šķērso 1 mezglu vienā atkārtojumā

Divi mezgli šķērso dažādus ātrumus. Tādējādi viņi tiksies, ja būs cilpa LinkedList.

Interesanti raksti...