如何在Swift扩展中反转链接列表?

时间:2016-04-19 03:31:06

标签: swift extension-methods singly-linked-list

我想在extension中撤消单链接列表,但最后它失败了。有人帮我吗?感谢。

   public class List<T: Equatable> {
        var value: T!
        var nextItem: List<T>?

   public convenience init!(_ values: T...) {
        self.init(Array(values))
   }

   init!(var _ values: Array<T>) {
        if values.count == 0 {
            return nil
        }
        value = values.removeFirst()
        nextItem = List(values)
     }
 }



 // Reverse a linked list.
 extension List {
     func reverse() {

     }
 }

1 个答案:

答案 0 :(得分:4)

我有一个解决方案。请阅读评论,这些也可以从代码中看出来。我还添加了一个&#39;描述&#39;通过CustomStringConvertible到列表来帮助调试和打印。

public class List<T: Equatable>{
    var value: T!
    var nextItem: List<T>?

    public convenience init!(_ values: T...) {
        self.init(Array(values))
    }

    init!(_ values: Array<T>) {
        if values.count == 0 {
            return nil
        }
        var valuesCopy = values
        value = valuesCopy.removeFirst()
        nextItem = List(Array(valuesCopy))
    }



}

extension List : CustomStringConvertible{
    public var description: String {
        var desc = String()
        var listRef : List<T>? = self
        while listRef != nil {
            desc += "\((listRef?.value)!) "
            listRef = listRef?.nextItem
        }
        return desc
    }
}

extension List{
    func reverse() -> List?{

        // Iterate through each item, and reverse its link until you visit the last node in the list.
        // Once you reach the end, All items except the last one would have
        // their links reversed.
        var nextNode : List<T>? = self.nextItem
        var prevNode : List<T>? = nil
        var currentNode : List<T>? = self

        while nextNode != nil{

            currentNode?.nextItem = prevNode
            prevNode = currentNode
            currentNode = nextNode
            nextNode =  currentNode?.nextItem
        }

        //Ensure the last item in the list too has its links reversed.
        currentNode?.nextItem = prevNode

        return currentNode

    }

}

var list = List(1,2,3,5)

print(list ?? "Failed to create the list")


if let reversed = list.reverse(){
  print(reversed)
}