day14 leetcode-hot100-25(链表4)
141. 环形链表 - 力扣(LeetCode)
1.哈希集合
思路
将节点一个一个加入HashSet,并用contains判断是否存在之前有存储过的节点,如果有便是环,如果没有便不是环。
具体代码
/*** 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) {HashSet<ListNode> set = new HashSet<>();ListNode p = head;while(p!=null){if(set.contains(p)){return true;}set.add(p);p=p.next;}return false;}
}
2.快慢指针
优化空间复杂度为O(1)
思路
一个慢指针每次走1格,一个快指针每次走2格,如果存在环肯定会相遇,如果不存在,最后都为null.
具体代码
/*** 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){return false;}ListNode slow = head;ListNode fast = head.next;while(slow != null && fast != null){if(slow==fast){return true;}slow=slow.next;if(fast.next!=null){fast = fast.next.next;}else{return false;}}return false;}
}