swift - 如何反转 Swift 扩展中的链表?

标签 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() {

     }
 }

最佳答案

我这里有一个解决方案。请阅读评论,从代码中也可以看出这一点。此外,我还通过 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)
}

关于swift - 如何反转 Swift 扩展中的链表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36708041/

相关文章:

C#检查属性的扩展方法

c# - 使用 IsNullOrEmpty 扩展 String 类是否令人困惑?

c - 检查链表是否回文的问题

c - 如何检查c代码链表中的可用座位

algorithm - 链表中的循环检测算法如何工作

ios - swift xcode 隐藏特定 View 的导航栏

swift - UIWebView 未在 iOS 10 中加载

ios - 我怎样才能使我的第 3 方键盘显示 'Multiple Languages' 而不仅仅是 'English' ?

ios - 表格 View 中的图像在选择时会更改大小

c#-4.0 - 扩展方法可以修改扩展类值吗?