【发布时间】:2020-01-06 09:58:39
【问题描述】:
我正在尝试使用 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)
}
}
【问题讨论】:
-
看看this Floyd 算法的实现(Scott Hunter 在下面提到)。它不是很快,但你应该能够轻松地移植它。
-
没有理由将此问题标记为重复,因为它显然不是!正如我所说的其他编程语言的答案,但我不熟悉它们。那么有人可以帮助我如何在 Swift 中做到这一点吗?
-
弗洛伊德算法的哪些部分您需要帮助?你试过什么?
-
链接到的问题与语言无关,答案解释了算法(带有指向更多文档的链接)。这些示例是用 Java 等编写的,但是一旦你理解了 idea,它应该很容易在 Swift 中实现。
标签: swift algorithm data-structures linked-list