判断给定的链表中是否有环
扩展:
你能给出不利用额外空间的解法么?
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
//快慢指针找中点slow
ListNode slow =head;
ListNode fast=head;
while(fast!=null&&fast.next!=null) {
slow = slow.next;
fast = fast.next.next;
//快慢指针重合必有环
if (slow == fast)
return true;
}
//若是空链表或者是只有一个元素,一定不是环
if(fast==null ||fast.next==null){
return false;
}
//???????加上以后效率变快?????????
if (slow == fast)
return true;
return false;
}
}
本文介绍了一种使用快慢指针技术判断链表是否存在环的高效算法。通过两个速度不同的指针遍历链表,若存在环则快慢指针必定会相遇。此方法无需额外空间,适用于各种链表结构。
475

被折叠的 条评论
为什么被折叠?



