LoginSignup
0
0

More than 3 years have passed since last update.

Leetcode #206: Reverse Linked List

Last updated at Posted at 2019-06-10

Solution 1: Iterative

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

Solution 2: Recursive

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

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0