【问题标题】:Insert node in singly linked list in swift playground在 Swift Playground 的单链表中插入节点
【发布时间】:2019-01-27 07:10:19
【问题描述】:

给定一个单链表,任务是编写一个程序将该元素插入到 Swift 的链表中。

【问题讨论】:

    标签: swift data-structures linked-list swift-playground


    【解决方案1】:
    import UIKit
    
    class Node<T: Equatable>{
        var value:T?
        var nextNode:Node?
    }
    
    class LinkedList<T: Equatable>{
        var headNode = Node<T>()
    
        func insert(value: T){
    
            if headNode.value == nil{
                headNode.value = value
            }else{
                var lastNode = headNode
                while lastNode.nextNode != nil {
                    lastNode = lastNode.nextNode!
                }
                let newNode: Node = Node<T>()
                newNode.value = value
                lastNode.nextNode = newNode
            }
        }
    
       func printAllKeys() {
            var currentNode: Node! = headNode
            print("---------------")
            while currentNode != nil && currentNode.value != nil {
                print("The item is \(currentNode.value!)")
                currentNode = currentNode.nextNode
            }
        }
    }
    
    var list = LinkedList<Int>()
    list.insert(value: 5)
    list.insert(value: 10)
    list.printAllKeys()
    

    【讨论】:

      猜你喜欢
      • 2015-10-20
      • 2018-07-28
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多