判斷給定的鏈表中是否有環。如果有環則返回true,否則返回false。
解題思路:設置兩個指針,slow和fast,fast每次走兩步,slow每次走一步,如果有環的話fast一定會追上slow,判斷fast==slow或者fast.next==slow即可判斷
class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } } public class test1 { public boolean hasCycle(ListNode head) { if(head==null || head.next==null){ //頭指針為空或者只有頭節點,無環 return false; } ListNode slow,fast = new ListNode(0); slow = head.next; fast = head.next.next; while(true){ if(fast==null||fast.next==null){ //fast走到鏈表尾 return false; }else if(fast.next==slow || fast==slow){ return true; }else{ slow = slow.next;// slow每次走一步 fast = fast.next.next;//fast每次走兩步 } } } public static void main(String[] args) { ListNode node1 = new ListNode(1),node2 = new ListNode(2),node3 = new ListNode(3),node4=new ListNode(4); node1.next=node2; node2.next=node3; node3.next=node4; node4.next=node1; test1 test = new test1(); System.out.println(test.hasCycle(node1)); } }