【数据结构】28、判断链表是否有环

博主因小米电话面试被问到判断链表是否有环的问题,遂实现该算法。介绍了链表内部类用于调试,给出测试类及结果。对比两种方式,方式一空间占用大、时间复杂度低,可定位环节点;方式二空间占用小、时间复杂度高,无法定位环节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

因为最近小米电话面试被问到如何判断一个链表是否有环,那今天正好实现以下这个算法

1.链表

package y2019.Algorithm.LinkedList;

/**
 * @ProjectName: cutter-point
 * @Package: y2019.Algorithm.LinkedList
 * @ClassName: FindRing
 * @Author: xiaof
 * @Description: 现在存在一条链表,寻找这个链表是否存在环
 * @Date: 2019/6/24 9:12
 * @Version: 1.0
 */
public class FindRing {

    public class Node {
        private String key;
        private String value;
        private Node next;

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public String getValue() {
            return value;
        }

        public void setValue(String value) {
            this.value = value;
        }

        public Node getNext() {
            return next;
        }

        public void setNext(Node next) {
            this.next = next;
        }
    }

    //链表头结点
    private Node ringHead;
    private Node ringTail;
    private int length;

    public FindRing() {
        ringHead = ringTail = null;
    }

    //创建一个长度为n的链表
    public FindRing(int length) {
        ringHead = ringTail = null;
        Node curNode = ringHead;
        for(int i = 0; i < length; ++i) {
            if(ringHead == null) {
                ringHead = new Node();
                ringHead.key = i + " " + System.currentTimeMillis();
                curNode = ringHead;
                ringTail = curNode;
            } else if (curNode.next == null) {
                curNode.next = new Node();
                curNode = curNode.next;
                curNode.key = i + " " + System.currentTimeMillis();
                ringTail = curNode;
            }
        }
        this.length = length;
    }

    public int size() {
        return length;
    }

    public void add(Node newNode) {
        //添加节点进入链表
        //尾部插入
        if(ringTail == null) {
            ringTail = newNode;
            ringTail = ringTail.next;
        } else {
            Node temp = ringTail.next;
            temp = newNode;
            ringTail = temp.next;
        }
        ++length;
    }

    public Node getByIndex(int index) {
        Node resultNode = ringHead;
        for(int i = 1; i < index; ++i) {
            resultNode = resultNode.next;
        }
        return resultNode;
    }

    public Node getRingHead() {
        return ringHead;
    }

    public void setRingHead(Node ringHead) {
        this.ringHead = ringHead;
    }

    public Node getRingTail() {
        return ringTail;
    }

    public void setRingTail(Node ringTail) {
        this.ringTail = ringTail;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }
}

 

内部类的使用,是为了方便调试

测试类:

package LinkedList;

import org.junit.jupiter.api.Test;
import y2019.Algorithm.LinkedList.FindRing;

import java.util.HashSet;
import java.util.Set;

/**
 * @ProjectName: cutter-point
 * @Package: LinkedList
 * @ClassName: Test1
 * @Author: xiaof
 * @Description: ${description}
 * @Date: 2019/6/24 9:31
 * @Version: 1.0
 */
public class Test1 {

    @Test
    public void test1 () {
        //判断一个链表是否有环
        //1.实现链表set方式,也就是通过hashcode进行定位
        FindRing findRing = new FindRing(15);

        //创建环节点
        int ringIndex = (int) (Math.random() * 10);
        ringIndex = 5;
        FindRing.Node ringNode = findRing.getByIndex(ringIndex);
        FindRing.Node tailNode = findRing.getRingTail();
        tailNode.setNext(ringNode);

        //开始判断是否有环
        Set set = new HashSet();
        //循环遍历链表,直到得到重复的
        FindRing.Node indexNode = findRing.getRingHead();
        int indexCount = 0;
        while(true) {
            if(indexNode == null) {
                System.out.println("无环");
                break;
            }
            if(set.contains(indexNode)) {
                System.out.println("有环,key:" + indexNode.getKey() + " 遍历次数:" + indexCount);
                break;
            }
            set.add(indexNode);
            indexNode = indexNode.getNext();
            indexCount += 1;
        }

        System.out.println("结束遍历");

    }

    @Test
    public void test2 () {
        //判断一个链表是否有环
        //1.通过2个指针同时查询,直到两个指针指向同一个节点作为有环,如果结束,那么无换
        FindRing findRing = new FindRing(15);

        //创建环节点
        int ringIndex = (int) (Math.random() * 10);
        ringIndex = 5;
        FindRing.Node ringNode = findRing.getByIndex(ringIndex);
        FindRing.Node tailNode = findRing.getRingTail();
        tailNode.setNext(ringNode);

        //开始判断是否有环
        FindRing.Node index1 = findRing.getRingHead();
        FindRing.Node index2 = findRing.getRingHead().getNext();
        int indexCount = 0;
        int indexCount2 = 0;
        //第一个每次遍历一个,第二个每次遍历2个
        while (true) {

            if(index1 == null || index2 == null || index2.getNext() == null) {
                System.out.println("无环");
                break;
            }

            if(index1 == index2) {
                System.out.println("有环,key:" + index1.getKey() + " 遍历次数1:" + indexCount + " 遍历次数2:" + indexCount2);
                break;
            }

            indexCount += 1;
            indexCount2 += 2;
            index1 = index1.getNext();
            index2 = index2.getNext().getNext();
        }

        System.out.println("结束遍历");
    }
}

 

结果:

测试一:

 

测试二:

 

 从这里我们可以判断到第二个方法并不能定位到产生环的节点是哪个节点,并且循环次数比第一个多

总结:

方式一:对空间占用比较大,但是时间复杂度底,并且可以定位到产生环节点的位置

方式二:对空间占用比较小,但是时间复杂度高,并且无法定位到具体产生环的节点

 

转载于:https://www.cnblogs.com/cutter-point/p/11075701.html

### 判断链表是否存在算法 判断链表是否存在是一个经典的数据结构问题,通常可以通过多种方法实现。以下是几种常见且有效的解决方案。 #### 方法一:快慢指针法 快慢指针法是一种高效的方法,用于检测链表是否存在。该方法的核心思想是定义两个指针——一个“快指针”和一个“慢指针”,它们分别以不同的速度遍历链表。具体来说,“慢指针”每次向前移动一步,而“快指针”每次向前移动两步[^1]。如果链表存在,则这两个指针最终会在某个节点相遇;如果没有,则“快指针”会先到达链表末尾并返回 `null`。 下面是基于 Java 的快慢指针法实现: ```java public class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } } public boolean hasCycle(ListNode head) { if (head == null || head.next == null) { return false; // 链表为空或者只有一个节点时不可能有 } ListNode slow = head; ListNode fast = head; while (fast != null && fast.next != null) { // 当前节点及其下一节点均不为空 slow = slow.next; // 慢指针走一步 fast = fast.next.next; // 快指针走两步 if (slow == fast) { // 如果两者相等则说明存在 return true; } } return false; // 若退出循则不存在 } ``` 这种方法的时间复杂度为 O(n),空间复杂度为 O(1)[^3]。 --- #### 方法二:哈希集合法 另一种常用的方法是利用哈希集合记录已经访问过的节点。当遍历链表时,将当前节点存入集合中。如果发现某节点已经在集合中存在,则表明链表中有;反之,若成功遍历至链表末端,则表示无。 下面展示了 Python 中的实现方式: ```python class ListNode: def __init__(self, x): self.val = x self.next = None def has_cycle(head): visited_nodes = set() # 创建一个空集合作为存储已访问节点的空间 current_node = head while current_node is not None: # 只要当前节点非空就继续执行 if current_node in visited_nodes: # 发现重复节点意味着存在路 return True visited_nodes.add(current_node) # 将新遇到的节点加入到集合当中去 current_node = current_node.next # 移动到下一个节点位置上去 return False # 完整扫描完毕之后仍然未找到任何重复项的话就可以断定是没有闭的情况发生啦~ ``` 此方法虽然简单易懂,但由于需要额外维护一个哈希集合,因此其空间复杂度较高,达到 O(n)[^2]。 --- #### 输入输出示例 假设我们有一个链表 `{3, 2, 0, -4}` 并且知道其中确实含有(第二个参数设为任意正数),那么调用上述任一函数都会返回布尔值 `True` 表明存在状连接关系[^4][^5]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值