leetcode [#141]

目录

题目

Given a linked list, determine if it has a cycle in it.


解决方案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
/**
* 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) {
ListNode p = head;
HashSet<ListNode> arr = new HashSet<>();

while(p != null){
if(arr.add(p) == false) {
return true;
}
p = p.next;
}
return false;
}
}

注意事项

  1. 使用java中HashSet的特性:add(E e) 方法用于为指定的元素添加到这个组,如果它是不存在的,将新元素加入HashSet,并返回true;如果此set已经包含该元素,则调用设定不变,并返回false。
  2. 使用“双指针”的方法更快:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    public boolean hasCycle(ListNode head) {
    if(head==null) return false;
    ListNode walker = head;
    ListNode runner = head;
    while(runner.next!=null && runner.next.next!=null) {
    walker = walker.next;
    runner = runner.next.next;
    if(walker==runner) return true;
    }
    return false;
    }