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

2023-03-15,,

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;
}
}

 

141. Linked List Cycle(判断链表是否有环)的相关教程结束。

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

下载本文的Word格式文档,以方便收藏与打印。