LeetCode刷题EASY篇Linked List Cycle

题目

判断一个链表是否有环

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

%e9%93%be%e8%a1%a8%e5%9b%be1

我的尝试

没有思路

正确解法

1.利用额外空间

利用set存储访问过的节点,如果已经访问过,表示有环。时间复杂度O(n),空间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) {
        Set<ListNode> set=new HashSet();
        while(head!=null){
            if(set.contains(head)){
                return true;
            }
            else{
                set.add(head);
            }
            head=head.next;
        }
        return false;
    }
}

2. 两个指针

空间复杂度降为O(1)

一个快指针,一个满指针,如果有环,终将相遇。

/**
 * 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 slow=head;
        ListNode fast=head.next;
        while(slow!=fast){
            if(fast==null||fast.next==null){
                return false;
            }
            slow=slow.next;
            fast=fast.next.next;
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/hanruikai/article/details/84885569
今日推荐