swift版本反转链表

一、定义链表节点

class ListNode {
    var val: Int
    var next: ListNode?
    
    init(_ val: Int) {
        self.val = val
        self.next = nil
    }
}

二、反转方法

 func reverList(headNode: ListNode) -> ListNode {
           var pre: ListNode?
           var next: ListNode?
           var cur: ListNode? = headNode
           while cur != nil  { //cur 依次尾部移动, cur.next 总是pre ,中间变量next 为了记录cur要向前移动的位置。
                next = cur?.next
                cur?.next = pre
                pre = cur
                cur = next
            }
            // 循环结束的条件是cur == nil 所以头结点是pre
            return pre!
        }

三、 override func viewDidLoad() 中调用

override func viewDidLoad() {
        let alist = ListNode(1)
        let blist = ListNode(2)
        let clist = ListNode(3)
        let dlist = ListNode(4)
           
        alist.next = blist
        blist.next = clist
        clist.next = dlist
           
        let newlist = reverList(headNode: alist)
       
        print("依次反转后-\(newlist.val)")
        print("依次反转后-\(newlist.next!.val)")
        print("依次反转后-\(newlist.next!.next!.val)")
        print("依次反转后-\(newlist.next!.next!.next!.val)")
    
    }

打印
依次反转后-4
依次反转后-3
依次反转后-2
依次反转后-1

你可能感兴趣的:(swift版本反转链表)