头图

1. 题目

描述

判断给定的链表中是否有环。如果有环则返回true,否则返回false。

数据范围:链表长度 0≤n≤10000,链表中任意节点的值满足 |val| <= 100000

要求:空间复杂度 O(1),时间复杂度 O(n)

输入分为两部分,第一部分为链表,第二部分代表是否有环,然后将组成的head头结点传入到函数里面。-1代表无环,其它的数字代表有环,这些参数解释仅仅是为了方便读者自测调试。实际在编程时读入的是链表的头节点。

例如输入{3,2,0,-4},1时,对应的链表结构如下图所示:


可以看出环的入口结点为从头结点开始的第1个结点(注:头结点为第0个结点),所以输出true。

示例1

输入:

{3,2,0,-4},1

返回值:

true

说明:

第一部分{3,2,0,-4}代表一个链表,第二部分的1表示,-4到位置1(注:头结点为位置0),即-4->2存在一个链接,组成传入的head为一个带环的链表,返回true             

示例2

输入:

{1},-1

返回值:

false

说明:

第一部分{1}代表一个链表,-1代表无环,组成传入head为一个无环的单链表,返回false             

示例3

输入:

{-1,-7,7,-4,19,6,-9,-5,-2,-5},6

返回值:

true

2. 解题思路

如下图所示,链表1不存在环(最后一个节点指向Null),而链表2存在环(最后一个节点的指针域指向了第二个节点)。


判断链表是否存在环有个小技巧快慢指针法。定义2个指针变量(即快慢指针),初始化时快慢指针都指向头节点,每次快指针每次移动 2 个节点,慢指针每次移动 1 个节点。如果 快指针指向的节点为null或者快指针指向节点的下一个节点为空,则链表没有环;如果快慢指针相遇则有环。

假如存在以下环链表,如下图所示:


判断链表是否有环步骤如下:
第一步:定义快慢指针。


第二步:移动快慢指针。快指针fast移动2个节点,指向0节点;慢指针slow移动1个节点,指向2节点。


快指针fast再移动两个节点,这时会指向节点2;慢指针slow移动1个节点,指向0节点。


快指针fast再移动两个节点,这时会指向节点-4;慢指针slow移动1个节点,也指向-4节点。此时快慢指向都指向-4节点,则链表存在环。


如果文字描述的不太清楚,你可以参考视频的详细讲解。
Python版本:https://www.bilibili.com/cheese/play/ep1370262
Java版本:https://www.bilibili.com/cheese/play/ep1366718
Golang版本:https://www.bilibili.com/cheese/play/ep13643953

3.编码实现

3.1 Python编码实现

class ListNode:
    def __init__(self, x):
        self.val = x  # 链表的数值域
        self.next = None  # 链表的指针域


# 从链表节点尾部添加节点
def insert_node(node, value):
    if node is None:
        print("node is None")
        return
    # 创建一个新节点
    new_node = ListNode(value)
    cur = node
    # 找到链表的末尾节点
    while cur.next is not None:
        cur = cur.next
    # 末尾节点的next指针域连接新节点
    cur.next = new_node


# 打印链表(从链表头结点开始打印链表的值)
def print_node(node):
    cur = node
    # 遍历每一个节点
    while cur is not None:
        print(cur.val, end="\t")
        cur = cur.next  # 更改指针变量的指向
    print()


#
#
# @param head ListNode类
# @return bool布尔型
#
class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        # write code here
        if head is None:
            return False

        # 1. 定义快慢指针
        fast = head
        slow = head

        # 2.移动快慢指针
        while fast is not None and fast.next is not None:
            fast = fast.next.next  # 快指针每次移动2个节点(快指针每次走2步)
            slow = slow.next  # 慢指针每次移动1个节点(慢指针每次走一步)
            if fast == slow:
                return True  # 快慢指针相遇,有环
        # 快指针对应的节点为null  或者 快指针对应节点的下一个节点为null,则没有环
        return False


if __name__ == '__main__':
    head = ListNode(3)
    head.next = ListNode(2)
    head.next.next = ListNode(0)
    head.next.next.next = ListNode(-4)

    #head.next.next.next.next = head.next

    s = Solution()
    has_cycle = s.hasCycle(head)
    print(has_cycle)

3.2 Java编码实现

package LL06;


public class Main {
    //定义链表节点
    static class ListNode {
        private int val;  //链表的数值域
        private ListNode next; //链表的指针域

        public ListNode(int data) {
            this.val = data;
            this.next = null;
        }
    }

    //添加链表节点
    private static void insertNode(ListNode node, int data) {
        if (node == null) {
            return;
        }
        //创建一个新节点
        ListNode newNode = new ListNode(data);
        ListNode cur = node;
        //找到链表的末尾节点
        while (cur.next != null) {
            cur = cur.next;
        }
        //末尾节点的next指针域连接新节点
        cur.next = newNode;
    }

    //打印链表(从头节点开始打印链表的每一个节点)
    private static void printNode(ListNode node) {
        ListNode cur = node;
        //遍历每一个节点
        while (cur != null) {
            System.out.print(cur.val + "\t");
            cur = cur.next; //更改指针变量的指向
        }
        System.out.println();
    }


    public static class Solution {
        /**
         * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
         *
         * @param head ListNode类
         * @return boolean
         */
        public boolean hasCycle(ListNode head) {
            // write code here
            if (head == null) {
                return false;
            }
            // 1. 定义快慢指针
            ListNode fast = head;
            ListNode slow = head;

            // 2. 移动快慢指针
            while (fast != null && fast.next != null) {
                fast = fast.next.next; //快指针每次移动2个节点(快指针每次走2步)
                slow = slow.next; //慢指针每次移动1个节点(慢指针每次走一步)
                if (slow == fast) {
                    return true;
                }
            }
            //快指针对应的节点为null 或者 快指针对应节点的下一个节点为null,则没有环
            return false;
        }
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(3);
        head.next = new ListNode(2);
        head.next.next = new ListNode(0);
        head.next.next.next = new ListNode(-4);

       //head.next.next.next.next = head.next;
        Solution solution = new Solution();
        boolean hasCycle = solution.hasCycle(head);
        System.out.println(hasCycle);
    }
}

3.3 Golang编码实现

package main

import (
    "fmt"
)

// ListNode 定义链表节点
type ListNode struct {
    Val  int       //链表的数值域
    Next *ListNode //链表的指针域
}

/**
 *
 * @param head ListNode类
 * @return bool布尔型
 */
func hasCycle(head *ListNode) bool {
    // write code here
    if head == nil {
        return false
    }
    // 1. 定义快慢指针
    slow := head
    fast := head
    // 2. 移动快慢指针
    for fast != nil && fast.Next != nil {
        fast = fast.Next.Next //快指针每次移动2个节点(快指针每次走2步)
        slow = slow.Next      //慢指针每次移动1个节点(慢指针每次走一步)
        if fast == slow {
            return true
        }
    }
    //快指针对应的节点为null 或者 快指针对应节点的下一个节点为null,则没有环
    return false
}

func main() {
    head := ListNode{Val: 3}
    head.Next = &ListNode{Val: 2}
    head.Next.Next = &ListNode{Val: 0}
    head.Next.Next.Next = &ListNode{Val: -4}

    //head.Next.Next.Next.Next = head.Next

    cycle := hasCycle(&head)
    fmt.Println(cycle)

}

// Insert 从链表节点尾部添加节点
func (ln *ListNode) Insert(val int) {
    if ln == nil {
        return
    }
    //创建一个新节点
    newNode := &ListNode{Val: val}
    cur := ln
    //找到链表的末尾节点
    for cur.Next != nil {
        cur = cur.Next
    }
    //末尾节点的next指针域连接新节点
    cur.Next = newNode
}

// Print 从链表头结点开始打印链表的值
func (ln *ListNode) Print() {
    if ln == nil {
        return
    }
    cur := ln
    //遍历每一个节点
    for cur != nil {
        fmt.Print(cur.Val, "\t")
        cur = cur.Next //更改指针变量的指向
    }
    fmt.Println()
}

如果上面的代码理解的不是很清楚,你可以参考视频的详细讲解。

4.小结

判断链表是否存在环有个小技巧快慢指针法。定义2个指针变量(即快慢指针),初始化时快慢指针都指向头节点,每次快指针每次移动 2 个节点,慢指针每次移动 1 个节点。如果 快指针指向的节点为null或者快指针指向节点的下一个节点为空,则链表没有环;如果快慢指针相遇则有环。

更多算法视频讲解,你可以从以下地址找到:

对于链表的相关操作,我们总结了一套【可视化+图解】方法,依据此方法来解决链表相关问题,链表操作变得易于理解,写出来的代码可读性高也不容易出错。具体也可以参考视频详细讲解。

今日佳句:问渠那得清如许?为有源头活水来。


好易学数据结构
1 声望0 粉丝