鏈表節(jié)點:
class ListNode {
int val;
ListNode next = null;
public ListNode(int a){
this.val = a;
}
}
判斷由上訴節(jié)點組成的鏈表中是否存在環(huán)
思路:
用兩個指針(cur1和cur2)指向鏈表的頭部肮韧,一個指針每次向后走一個節(jié)點,另一個指針每次向后走兩個節(jié)點雾狈,如果有環(huán)列敲,則cur1和cur2必然在某個時候相等。
代碼實現(xiàn):
public static boolean isCycle(ListNode head){
if(head == null || head.next == null){
return false;
}
ListNode cur1 = head;
ListNode cur2 = head;
while(cur1.next != null && cur2.next != null){
cur1 = cur1.next;
cur2 = cur2.next;
if(cur2.next == null){
break;
}
cur2 = cur2.next;
if(cur1 == cur2){
return true;
}
}
return false;
}