如何比较两个通用链表? [英] How can two generic linked list in swift can be compared?
问题描述
我有一个通用链表,如果每个节点值相同且顺序正确,我可以检查两个链表是否相等. 我有一个将链接列表分为两部分的函数,稍后我要检查两个列表在其节点中是否具有相同的值.
I have a generic linked list and I can check if two linked list are equal if each of the node value are same and are in order. I have a function which divides linked list in two part and later I want to check two list has same value in it's node.
func divideList(atIndex index:Int) -> (first: LLGeneric<T>?,second: LLGeneric<T>?)
我正在寻找用例,可以在分割并比较后(在反转一个列表之后)检查链接列表中的回文.
I looking it for my use case where I can check palindrome in linked list after dividing and then comparing ( after reversing one list).
注意:我的链表节点是通用的
Note: my linked list node is generic something like
class LLGenericNode<T> {
var value: T
var next: LLGenericNode?
weak var previous: LLGenericNode?
init(_ value: T) {
self.value = value
}
}
推荐答案
为了比较值,您必须要求T
为Equatable
:
In order to compare values you have to require that T
is Equatable
:
class LLGenericNode<T: Equatable> {
// ...
}
然后您可以通过首先比较值来实现==
.
如果值相等,则对列表尾部进行递归比较.
Then you can implement ==
by comparing the values first.
If the values are equal, the list tails are compared recursively.
extension LLGenericNode: Equatable {
static func ==(lhs: LLGenericNode<T>, rhs: LLGenericNode<T>) -> Bool {
if lhs.value != rhs.value {
return false
}
switch (lhs.next, rhs.next) {
case (nil, nil):
// Both tails are == nil:
return true
case let (lvalue?, rvalue?):
// Both tails are != nil:
return lvalue == rvalue // Recursive call
default:
// One tails is nil and the other isn't:
return false
}
}
}
这篇关于如何比较两个通用链表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!