您的位置:首页 > 编程语言 > Java开发

leetcode-Java-141. Linked List Cycle.java

2016-06-04 10:58 393 查看
思路:

方法1.可以使用hashset,重复返回true

方法2:使用两个指针,fast和slow,两个指针重合时

public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null)
return false;

HashSet<ListNode> set = new HashSet<ListNode>();

while(head!=null) {
if(set.contains(head)) {
return true;
}
set.add(head);
head = head.next;
}
return false;
}
}


public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null)
return false;

ListNode fast = head,
slow = head;

while(true) {
if(fast.next != null && fast.next.next!=null) {
fast = fast.next.next;
slow = slow.next;
}else{
return false;
}
if(slow == fast) {
return true;
}

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: