[leetcode] 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?

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

思路:CC150中的题目,采用一快一慢两指针来解决。慢指针每次走一步,快指针每次走两步,如果快指针追上慢指针,则证明有环。

/**
 * refer to CC150
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;

        while (fast!=null&&fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;

            if (slow == fast)
                return true;
        }

        return false;

    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        head.next.next.next.next.next = head.next.next;

        System.out.println(new Solution().hasCycle(head));

    }

}

第二遍记录:双指针,写完了,null,1个节点,2个节点的情况测试下。

public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        
        while(fast!=null&&fast.next!=null){
            fast= fast.next.next;
            slow =slow.next;
            if(fast==slow)
                return true;
        }
        return false;
        
    }
}

第三遍:写法完全一样

  注意自助测试,null的情况,一个节点,两个节点等等。

原文地址:https://www.cnblogs.com/jdflyfly/p/3829483.html