解题思路
141. 环形链表
该题有二种思路
- 哈希表:用hashSet记录已经遍历过的结点。
- 快慢链表:快链表移动的快,慢链表移动的慢,若两指针相遇则判断有环
代码
方法一:哈希表
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
//哈希表
public static boolean hasCycle(ListNode head) {
Set<ListNode> hash = new HashSet<>();
while(head!=null) {
if(hash.contains(head)) {
return true;
}
hash.add(head);
head = head.next;
}
return false;
}
}
方法二:快慢链表
public class Solution {
//快慢链表,如果不是环,慢链表追不上快链表,如果是环,慢链表就会追上快链表
public static boolean hasCycle(ListNode head) {
ListNode fast_node = head;
ListNode slow_node = head;
while(fast_node!=null && fast_node.next!=null) {
fast_node = fast_node.next.next;
slow_node = slow_node.next;
if(fast_node == slow_node) {
return true;
}
}
return false;
}
}