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

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;
}
}
 
上一篇:虔诚的墓主人(BZOJ1227)(洛谷P2154)解题报告


下一篇:洛谷 P3956 棋盘(BFS)