美文网首页
利用快慢指针获取链表闭环的入口

利用快慢指针获取链表闭环的入口

作者: 梁森的简书 | 来源:发表于2021-02-01 23:44 被阅读0次

    创建两个指针分别指向头节点,同时创建一个临时空指针,当快慢指针相遇的时候(有闭环),将临时空指针指向头节点,同时继续继续下次循环,当慢指针和临时指针相遇,则此节点就是闭环入口。

    /// 快慢指针获取环状链表的入口
        private func testEntrance() {
            let firstNode = Node(item: "1", next: nil)
            let secondNode = Node(item: "2", next: nil)
            let thirdNode = Node(item: "3", next: nil)
            let forthNode = Node(item: "4", next: nil)
            let fifthNode = Node(item: "5", next: nil)
            let sixthNode = Node(item: "6", next: nil)
            let seventhNode = Node(item: "7", next: nil)
            let eightNode = Node(item: "8", next: nil)
            
            firstNode.next = secondNode
            secondNode.next = thirdNode
            thirdNode.next = forthNode
            forthNode.next = fifthNode
            fifthNode.next = sixthNode
            sixthNode.next = seventhNode
            seventhNode.next = eightNode
            
            eightNode.next = fifthNode
            
            let node = getEntrance(firstNode: firstNode)
            print("node.item:\(node.item ?? "")")
        }
        
        private func getEntrance(firstNode: Node?) -> Node {
            var fast = firstNode
            var slow = firstNode
            var temp: Node?
            while fast != nil && fast!.next!.next != nil {
                fast = fast!.next!.next!
                slow = slow!.next!
                if fast! == slow! { // 应该是比较节点是否相同
                    if temp == nil {    // 被赋值之后就不再管快慢指针了
                        temp = firstNode
                        continue    // 循环体立刻停止本次循环迭代,重新开始下次循环迭代
                    }
                }
                if temp != nil {
                    temp = temp!.next!
                    if slow! == temp! {
                        break
                    }
                }
            }
            return slow!
        }
    

    demo地址:https://github.com/yangguanghei/studyDateStructure

    相关文章

      网友评论

          本文标题:利用快慢指针获取链表闭环的入口

          本文链接:https://www.haomeiwen.com/subject/nskdtltx.html