leetcode刷题题解——141.环形链表
作者:互联网
public boolean hasCycle(ListNode head) {
if (head==null||head.next==null) return false;
ListNode slow = head;
ListNode fast = head.next;
while (fast!=null&&fast.next!=null){
slow = slow.next;
fast = fast.next.next;
if(fast==slow) return true;
}
return false;
}
判断一个链表是否有环:快慢指针(个人理解:其实就是追赶问题)
- 设置两个指针,一快一慢
- fast指针走两步,slow指针走一步
- 如果相遇,说明有环
- 如果fast== null或fast.next==null说明链表遍历到了尽头,即没环
标签:head,slow,141,题解,fast,next,链表,null 来源: https://blog.csdn.net/qq_53226437/article/details/122790409