链表环问题

题目

解法一 哈希表

  • 将遍历过的节点存入哈希表,利用哈希表数据唯一性
 /**
 * 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;
        Set<ListNode> s = new HashSet<>();
        while(head != null){
    
    
            if(!s.add(head)) return true;
            head = head.next;
        }
        return false;
    }
}

解法二(最优解) 快慢指针

  • 此解法空间复杂度O(1), 时间复杂度O(n)
/**
 * 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 slowPointer = head;
        ListNode fastPointer = head.next;
        while(slowPointer != fastPointer){
    
    
            if(fastPointer == null || fastPointer.next == null) //这里只需判断fastPointer
                return false;
            slowPointer = slowPointer.next;
            fastPointer = fastPointer.next.next;
        }
        return true;
    }
}

为什么快慢指针一定会相遇?

思考:如何计算出环的长度?

未完待续

猜你喜欢

转载自blog.csdn.net/rakish_wind/article/details/120120708