【问题标题】:How to reverse the Linked List in Swift extension?如何在 Swift 扩展中反转链表?
【发布时间】:2016-08-11 00:30:17
【问题描述】:

我想反转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() {

     }
 }

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 我收到错误 init menthod var is not allowed as a parameter 。任何解决方案
    • 刚刚编辑删除了 var 用法(这在 swift 3/4 中不起作用)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 2012-02-23
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    • 2016-02-19
    相关资源
    最近更新 更多