swift实现单链表逆序

文接上篇,地址: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

你可能感兴趣的:(swift实现单链表逆序)