算法训练 第三周

二、环形链表

在这里插入图片描述
本题给了我们一个链表的头节点,需要我们判断这个链表之中是否存在环状结构,如果存在返回true,如果不存在则返回false。

1.hash表

我们可以从头遍历整个链表,并将遍历到的节点放入一个hashset中,当我们遍历到的节点与hashset中的节点出现重复时就说明链表存在环,如果我们遍历完了整个链表那就说明不存在环,具体代码如下:

/**
 * 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 node = head;
        HashSet<ListNode> set = new HashSet<>();
        while(node != null) {
            if(set.contains(node)) {
                return true;
            }
            set.add(node);
            node = node.next;
        }
        return false;
    }
}
复杂度分析
  • 时间复杂度:O(n)。
  • 空间复杂度:O(n)。

2.双指针

我们可以定义两个指针来遍历这个链表,慢指针每次走一个节点,快指针每次走两个节点,如果在遍历的过程中快指针与慢指针相遇则说明有环,否则就没有环,具体代码如下:

/**
 * 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 f = head;
        ListNode s = head;
        while(f != null && f.next != null) {
            f = f.next.next;
            s = s.next;
            if(f == s) {
                return true;
            }
        }
        return false;
    }
}
复杂度分析
  • 时间复杂度:O(n)。
  • 空间复杂度:O(1)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值