English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans cet exemple, nous allons apprendre à détecter une boucle dans LinkedList en Java.
Pour comprendre cet exemple, vous devriez comprendre ce qui suitProgrammation JavaThème :
class LinkedList { // crée un objet de la classe Node // représente la tête de la liste Node head; // interne statique class statique Node { int value; // ربط كل عقدة بآلية التالية Node next; Node(int d) { value = d; next = null; } } // فحص وجود دائرة public boolean checkLoop() { // إنشاء مراجعين في بداية LinkedList Node first = head; Node second = head; while(first != null && first.next != null) { // تحريك المرجع الأول إلى عقدتين first = first.next.next; // تحريك المرجع الثاني إلى عقدة واحدة second = second.next; // إذا كانت المراجعتين متساويتين (تلاقي) if(first == second) { return true; } } return false; } public static void main(String[] args) { // إنشاء موضوع LinkedList LinkedList linkedList = new LinkedList(); // تعيين قيمة لكل عقدة في قائمة الاتصال linkedList.head = new Node(1); Node second = new Node(2); Node third = new Node(3); Node fourth = new Node(4); // ربط كل عقدة في سلسلة بعقدة التالية linkedList.head.next = second; second.next = third; third.next = fourth; // تنفيذ دورة في LinkedList fourth.next = second; // طباعة قيمة العقدة System.out.print("LinkedList: "); int i = 1; while (i <= 4) { System.out.print(linkedList.head.value + " "); linkedList.head = linkedList.head.next; i++; } // تنفيذ طريقة فحص الدائرة boolean loop = linkedList.checkLoop(); إذا (loop) { System.out.println("\nهناك حلقة في LinkedList."); } else { System.out.println("\nلا توجد حلقة في LinkedList."); } } }
نتائج الإخراج
LinkedList: 1 2 3 4 هناك حلقة في LinkedList
في هذا المثال، نحن نستخدم Java نحن نتحقق من LinkedList. لقد استخدمنا,
لاحظ رمز method checkLoop(). هنا، لدينا متغيران تسمى first،second،يتجولان في النود في LinkedList.
first - تستخدم إثنتين من النود في التدوير مرة واحدة
second - تستخدم واحدة من النود في التدوير مرة واحدة.
تتجولان في إحداثيتين مختلفتين. لذلك، إذا كان هناك حلقة في LinkedList، ستلتقيان.