java算法判断链表有没有闭环_利用快慢指针查看链表是否有闭环

创建两个指针分别指向头节点,快指针每次移动两位,慢指针每次移动一位,如果快慢指针能相遇则说明链表有闭环。

/// 快慢指针解决链表是否有闭环

private func testCircle() {

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 isCir = isCircle(firstNode: firstNode)

print("isCircle:\(isCir)")

}

private func isCircle(firstNode: Node) -> Bool {

var fast = firstNode

var slow = firstNode

while fast.next?.next != nil {

fast = fast.next!.next!

slow = slow.next!

if fast.item == slow.item { // 应该是比较节点是否相同

return true

}

}

return false

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值