gpt4 book ai didi

swift - 如何使用 Swift 检测链表中的循环/周期

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:49:28 27 4
gpt4 key购买 nike

<分区>

我正在尝试使用 Swift 检测链表中的循环/周期的函数。有人可以告诉我代码如何做到这一点吗?我在其他一些我不太熟悉的编程语言中找到的唯一答案

这是我目前正在处理的代码。

public class Node<Value> {

public var value: Value
public var next: Node?

public init(value: Value, next: Node? = nil) {
self.value = value
self.next = next
}
}

public struct LinkedList<Value> {

public var head: Node<Value>?
public var tail: Node<Value>?

public init() {}

public var isEmpty: Bool {
return head == nil
}

public mutating func push(_ value: Value) {
head = Node(value: value, next: head)
if tail == nil {
tail = head
}
}

public mutating func apped(_ value: Value) {

guard !isEmpty else {
push(value)
return
}
tail!.next = Node(value: value)

tail = tail!.next
}
}

extension Node: CustomStringConvertible {

public var description: String {
guard let next = next else {
return "\(value)"
}

return "\(value) -> " + String(describing: next) + " "
}
}

extension LinkedList: CustomStringConvertible {

public var description: String {
guard let head = head else {
return "Empty List"
}
return String(describing: head)
}
}

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com