循环链表:快慢指针

2021-07-09  本文已影响0人  段段小胖砸
image.png

解决方案1:循环链表遍历放入数组,然后循环看节点是否存在于数组中,比较简单,就不实现了
解决方案2:快慢指针

public class Solution {
    public boolean hasCycle(ListNode head) {
       if (head == null) {
           return  false;
       }
       //定义快慢指针
       ListNode slow = head;
       ListNode fast = head.next;
       //遍历链表: 快指针步长为2,慢指针步长为1
        while (fast != null && fast.next != null) {
            //当且仅当快慢指针重合:有环,操作结束
            if (slow == fast) {
                return true;
            }
            fast = fast.next.next;
            slow = slow.next;
        }

        //快指针为null,或其next指向null,没有环,返回false
        return false;
    }

    class ListNode {
       int val;
       ListNode next;
       ListNode(int x) {
           val = x;
           next = null;
       }
   }
}
//leetcode submit region end(Prohibit modification and deletion)

}
上一篇下一篇

猜你喜欢

热点阅读