題目:
給定一個鏈表,判斷鏈表中是否有環(huán)线召。
為了表示給定鏈表中的環(huán)铺韧,我們使用整數(shù) pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。 如果 pos 是 -1缓淹,則在該鏈表中沒有環(huán)哈打。
思路:
利用快慢指針,一個走兩步讯壶,一個走一步料仗。有環(huán)必相遇,無環(huán)則有一個會走到Null伏蚊。
代碼:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if( head == null ) return false;
ListNode l1 = head;
if( head.next == null ) return false;
ListNode l2 = head.next.next;
while( l1 != null && l2 != null && l2.next != null){
if( l1 == l2 ) return true;
l1 = l1.next;
l2 = l2.next.next;
}
return false;
}
}