Swift.反转链表

cubegao 2015-07-08 PM 471℃ 0条
题目描述:1->2->3->4,4->3->2->1
import Foundation

class For16Solution {
    func reversedListNode(_ head: ListNode?) -> ListNode? {
        if head == nil || head?.next == nil {
            return head
        }
        
        var pre : ListNode?
        var cur = head
        pre = nil

        while cur != nil {
            let tmp = cur?.next
            cur?.next = pre
            pre = cur
            cur = tmp
        }
        
        
        head?.next = nil
        
        return pre
    }
    
    func reversedListNode2(_ head: ListNode?) -> ListNode? {

        if head == nil || head?.next == nil {
            return nil
        }
        
        let newHead = reversedListNode2(head?.next)
        head?.next?.next = head
        head?.next = nil
        
        return newHead
    }
}

算法思想:迭代的话,使用使用头插法。

github地址:https://github.com/cubegao/LeetCode

标签: 算法

非特殊说明,本博所有文章均为博主原创。

评论啦~