Linked List Cycle ---LeetCode

来源:互联网 发布:编程找质数 编辑:程序博客网 时间:2024/06/05 16:22

https://leetcode.com/problems/linked-list-cycle/

解题思路:
判断链表有没有环。我们使用两个指针,一个一次走一步,一个一次走两步。如果链表有环,那么他们一定会相遇。

需要注意一下 while 的循环条件 fast.next != null && fast.next.next != null,如果没有后面一句那么在循环体里的 fast = fast.next.next 就会出现空指针异常。例:[1, 2]。

/** * 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) {        if(head == null) return false;        ListNode slow = head;        ListNode fast = head;        while(fast.next != null && fast.next.next != null){            slow = slow.next;            fast = fast.next.next;            if(slow == fast)                return true;        }        return false;    }}
0 0
原创粉丝点击