源地址:https://leetcode.com/problems/linked-list-cycle/
判断链表是否有环路
首先最开始想到的办法是存储访问过的节点,之后看当前节点的next是否指向已经遍历过的节点,这样的时间复杂度是O(n),空间复杂度也是O(n)。使用ArrayList存储会非常慢,使用hashmap存储大概运行时间6 ms, faster than 12.13% of Java online submissions for Linked List Cycle.
public class Solution { public boolean hasCycle(ListNode head) { if(head == null){ return false; } HashMap<ListNode, Integer> map = new HashMap<>(); int i = 0; while(head!= null){ map.put(head, i++); head = head.next; if(map.containsKey(head)){ return true; } } return false; } }
为了是空间复杂度降至O(1), 使用快慢指针的方法。如果存在环路, 那么快慢指针一定会在某一点相遇,就好像在操场上跑圈一样,快的人一定会赶上慢的人,
这样运行Runtime: 0 ms, faster than 100.00% of Java online submissions for Linked List Cycle.
/** * 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 fast = head; while(fast != null && fast.next!= null){ fast = fast.next.next; head = head.next; if(head == fast){ return true; } } return false; } }