swift实现单链表逆序

2018-03-16  本文已影响0人  黑刀秋水

文接上篇,地址:https://www.jianshu.com/p/68de9b3daa13

  //单链表的逆序实现
  func reverseList(_ headNode: inout Node){
        var pre:Node?
        var next:Node?
        var tempList:Node? = headNode
        while tempList != nil {
            next = tempList?.next
            tempList?.next = pre
            pre = tempList
            tempList = next
        }
        headNode = pre!
    } 

方法调用执行

let list1 = ListNode()
var node = list1.initListNodeFromTail2([3,5,12,20])
list1.printList(&node)
list1.reverseList(&node)
list1.printList(&node)

最后打印结果:20、12、5、3

上一篇下一篇

猜你喜欢

热点阅读