创建两个指针分别指向头节点,快指针每次移动两位,慢指针每次移动一位,如果快慢指针能相遇则说明链表有闭环。
/// 快慢指针解决链表是否有闭环
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
}