环形链表(简单)
2020年5月16日
题目来源:力扣
解题
看到题目,很容易想到用哈希表记录结点,如果出现一个出现过的结点,那就说明开始循环,返回true;若最后指向null,说明没有环,返回false。
但这种做法,额外用到了哈希表记录的空间,与题意不符。
/**
* 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) {
Set<ListNode> hh=new HashSet<>();
while(head!=null){
if(hh.contains(head)){
return true;
}
else{
hh.add(head);
}
head=head.next;
}
return false;
}
}
妙的是第二种方法,“快慢双指针”。像跑步的时候,跑得快的同学跑多几圈后总会追上跑得慢的同学,当他们身处同一位置的时候,相当于两个结点重复了,说明循环,返回true;若最后指向null,说明没有环,返回false。
/**
* 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 || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
}