LeetCode笔记:141. 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?

大意:

给出一个链表,判断它有没有回环。

进阶:
你能不能不用额外的空间来解决?

思路:

这道题我利用Java中Set集合的特性,即集合中不允许出现相同的对象。

我们遍历链表,边遍历边把每个节点放入一个Set集合中,并且每次都判断Set集合内对象的个数是否增加了,如果没增加,说明有相同的对象加入,也就是有回环了。

我看别人的解决办法,很多都是判断相邻的节点间有没有回环,其实不太理解,是不是回环只有相邻的这种情况呢,那如果存在大回环不是就判断不出来了么,还是觉得Set的方法比较保险。

代码(Java):

/** * 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;
        HashSet list = new HashSet();
        list.add(head);
        int num = 1;
        while (head.next != null) {
            list.add(head.next);
            num++;
            if (num > list.size()) return true;
            head = head.next;
        }
        return false;
    }
}

版权所有:http://blog.csdn.net/cloudox_

你可能感兴趣的:(LeetCode)