gpt4 book ai didi

swift - Swift 中的循环链表

转载 作者:行者123 更新时间:2023-11-28 11:09:34 26 4
gpt4 key购买 nike

我想确定我的链表是否为空,但是,我不能通过检查 head.next==tail 来做到这一点,因为我会得到一个错误,即二元运算符“==”不能应用于操作输入“LLNode?”。

import Foundation

class LLNode<T> {
var key: T!
var next: LLNode?
var previous: LLNode?
}

public class LinkedList<T: Equatable> {
private var head: LLNode<T> = LLNode<T>()
private var tail: LLNode<T> = LLNode<T>()

init() {
head.next = tail
head.previous = tail
tail.next = head
tail.previous = head
}

func isEmpty() {
return head.next == tail ? true : false
}
}

最佳答案

在这种情况下,您可能应该使用 === 运算符检查 headtail 是否是同一实例。请注意,这与 Swift 中的相等性测试不同。

== 检查对象是否相等,您必须自己定义,而 === 确定两个变量是否引用同一个实例。因此,您的支票应如下所示:

func isEmpty() -> Bool {
return head.next === tail
}

三元运算符不是必需的,因为比较运算符已经返回 Bool。

关于swift - Swift 中的循环链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35996843/

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