題目:判斷給定的鏈表中是否有環
思路:設置快慢指針,剛開始快慢指針同時指向某一個節點,然後進行next,當快慢指針再次相遇的時候,說明該鏈表有環。
代碼:
package com.company;
public class TestNo26 {
static class ListNode{
int val;
ListNode next;
ListNode(int x){
val = x;
next = null;
}
}
public static void main(String[] args) {
ListNode head = new ListNode(3);
head.next = new ListNode(4);
head.next.next = new ListNode(7);
head.next.next.next = new ListNode(6);
head.next.next.next.next = head;
TestNo26 t = new TestNo26();
System.out.println(t.hasCycle(head));
}
public boolean hasCycle(ListNode head) {
//快指針
ListNode fast = head;
//慢指針
ListNode slow = head;
while (fast != null && slow != null){
fast = fast.next.next;
slow = slow.next;
//當快指針與慢指針相遇的時候,則有環。
if(fast == slow){
return true;
}
}
return false;
}
}