206.反转链表

1.正向遍历,移动指针

class Solution {
    func reverseList(_ head: ListNode?) -> ListNode? {
        var pre: ListNode? = nil
        var current = head
        while current != nil {
            let tmp_next = current?.next
            current?.next = pre
            pre = current
            current = tmp_next
        }
        return current
    }
}

2.递归

class Solution {
    func reverseList(_ head: ListNode?) -> ListNode? {
        if head == nil || head?.next == nil {
            return head
        }
        let newHead = reverseList(head?.next)
        head?.next?.next = head
        head?.next = nil
        return newHead
    }
}

你可能感兴趣的:(206.反转链表)