How can two generic linked list in swift can be compared?

前提是你 提交于 2020-01-04 05:35:35

问题


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
    }
}

回答1:


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
        }
    }
}


来源:https://stackoverflow.com/questions/45663847/how-can-two-generic-linked-list-in-swift-can-be-compared

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!