美文网首页
反转链表-Swift

反转链表-Swift

作者: CocoaJason | 来源:发表于2020-12-10 10:19 被阅读0次
    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
    

    相关文章

      网友评论

          本文标题:反转链表-Swift

          本文链接:https://www.haomeiwen.com/subject/hgylgktx.html