141. Linked List Cycle

原题链接:https://leetcode.com/problems/linked-list-cycle/description/
直接上代码:

import java.util.HashSet;

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }

    public static void main(String[] args) {
        Solution s = new Solution();

        ListNode node1 = new ListNode(1);
        node1.next = new ListNode(2);
        node1.next.next = node1;
        System.out.println(s.hasCycle(node1));
        System.out.println(s.hasCycle2(node1));
    }

    /**
     * 我的方法,题目中要求不能使用额外的空间,但是我用了,所以说并不完美
     *
     * @param head
     * @return
     */
    public boolean hasCycle(ListNode head) {
        if (head == null) {
            return false;
        }

        HashSet<ListNode> nodes = new HashSet<>();
        nodes.add(head);
        while (head.next != null) {
            head = head.next;
            if (nodes.contains(head)) {
                return true;
            }
            nodes.add(head);
        }

        return false;
    }

    /**
     * 别人提交的答案,不得不说很牛逼啊
     *
     * @param head
     * @return
     */
    public boolean hasCycle2(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }

        ListNode p1 = head, p2 = head;
        while (p2 != null && p2.next != null) {
            p1 = p1.next;
            p2 = p2.next.next;
            if (p1 == p2) {
                return true;
            }
        }

        return false;
    }

    // 官方答案:官方答案给了两种,尼玛,就是上面的这两种了!
}
posted @ 2018-03-17 19:29  optor  阅读(107)  评论(1编辑  收藏  举报