Shark Deng

Interactive Designer @Shanju Design in Shanghai

touched caffe / mxnet / python / wordpress / bootstrap / Arduino / Raspberry Pi / webgl / three.js / PIXI / 3dMax

Email

Github

Swift – LinkList泛型链表

2019-11-14 03:24:26

class LinkList<T>: CustomDebugStringConvertible, ExpressibleByArrayLiteral {
    var head: Node?
    var tail: Node?
    typealias Element = T
    
    required init(arrayLiteral elements: Element...) {
        for i in elements {
            if head == nil {
                let newNode = Node(data: i)
                self.head = newNode
                self.tail = newNode
            } else {
                let newNode = Node(data: i)
                self.tail?.next = newNode
                self.tail = newNode
            }
        }
    }
    
    var debugDescription: String {
        var a: String = ""
        guard head != nil else { return "empty list" }
        a += head!.debugDescription
        
        var currentNode = head!
        while(true){
            guard let nextNode = currentNode.next else { break }
            a += nextNode.debugDescription
            currentNode = nextNode
        }
        
        return a
    }
    
    class Node: CustomDebugStringConvertible {
        var data: T
        var next: Node?
        
        init(data: T){
            self.data = data
        }
        
        var debugDescription: String {
            var a: String = ""
            if next != nil {
                a += "\(self.data) -> "
            } else {
                a += "*"
            }
            return a
        }
    }
}

 



——By SharkDeng
如果你喜欢我的文章,欢迎红包赞赏

Leave a Reply

Your email address will not be published. Required fields are marked *