双指针简单 leetcode141. 环形链表
程序员文章站
2024-03-08 18:39:16
...
双指针
/**
* 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 low = head;
if(low == null){
return false;
}
ListNode fast = head.next;
while(low != fast){
if(fast == null || fast.next == null){
return false;
}
low = low.next;
fast = fast.next.next;
}
return true;
}
}
哈希表
public class Solution {
public boolean hasCycle(ListNode head) {
Set<ListNode> set = new HashSet<>();
ListNode cur = head;
while(cur != null){
if(set.contains(cur)){
return true;
}
set.add(cur);
cur = cur.next;
}
return false;
}
}