Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路:使用快慢指針, fast每次跳兩個(gè)節(jié)點(diǎn),low一次跳一個(gè)節(jié)點(diǎn),如果fast或者low最后為null,說(shuō)明
鏈表沒(méi)有節(jié)點(diǎn). 如果fast和low相等,那么說(shuō)明鏈表存在環(huán)
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null){
return false;
}
ListNode lowerNode = head;
ListNode fastNode = head;
while(lowerNode != null && fastNode != null){
if(fastNode.next == null){
return false;
}
fastNode = fastNode.next.next;
lowerNode = lowerNode.next;
if(lowerNode == fastNode){
return true;
}
}
return false;
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者