反转链表-Swift

2020-12-10  本文已影响0人  CocoaJason
class ListNode {
    var val: Int
    var next: ListNode?
    
    init(val: Int) {
        self.val = val
    }
}

class Solution {
    class func Reverselist(head: ListNode?) -> ListNode? {
        var cur = head
        var pre: ListNode?
        var next: ListNode?
        
        while cur != nil {
            next = cur?.next
            cur?.next = pre
            pre = cur
            cur = next
        }
        return pre
    }
    
    class func printCurrent(head: ListNode?) {
        var cur = head
        if cur == nil {
            print("空链表")
        }
        var string = ""
        while cur != nil {
            string = string + "\(cur!.val)"  + " -> "
            cur = cur?.next
        }
        print(string + "Null")
    }
}

var head: ListNode?
        var pre: ListNode?
        for i in 1...5 {
            let cur = ListNode(val: i)
            if pre == nil {
                head = cur
                pre = head
            } else {
                pre?.next = cur
                pre = cur
            }
        }
        
        Solution.printCurrent(head: head)
        
        let reserver = Solution.Reverselist(head: head)
        Solution.printCurrent(head: reserver)

结果

1 -> 2 -> 3 -> 4 -> 5 -> Null
5 -> 4 -> 3 -> 2 -> 1 -> Null
上一篇下一篇

猜你喜欢

热点阅读