Leetcode:
141. Linked List Cycle

Method1
/**
* 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> nodesSeen = new HashSet<>();
while (head != null) {
if (nodesSeen.contains(head)) {
return true;
} else {
nodesSeen.add(head);
}
head = head.next;
}
return false;
}
}
Method2
/**
* 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 fast = head;
ListNode slow = head;
while(fast!=null && fast.next!=null){
fast = fast.next.next;
slow = slow.next;
if(fast==slow){
return true;
}
}
return false;
}
}
LeetCode 141. Linked List Cycle 解题
本文详细介绍了如何使用两种方法解决LeetCode上的141.Linked List Cycle问题,第一种方法通过使用HashSet来跟踪已访问过的节点,判断链表中是否存在环;第二种方法采用快慢指针技巧,高效检测链表是否循环。
373

被折叠的 条评论
为什么被折叠?



