141. Linked List Cycle(判断链表是否有环)

时间:2023-12-30 10:20:56

141. Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

利用快慢指针,如果相遇则证明有环

注意边界条件: 如果只有一个node.

 public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null || head.next==null) return false;
ListNode slower =head,faster = head;
while(faster!=null && faster.next!=null){
if(faster==slower) return true;
faster = faster.next.next;
slower = slower.next;
}
return false;
}
}