Swift solution


  • 0
    class Solution {
        // iterative
        func reverseList(_ head: ListNode?) -> ListNode? {
            var head = head
            var newHead: ListNode? = nil
            
            while head != nil {
                let next = head?.next
                head?.next = newHead
                newHead = head
                head = next
            }
            
            return newHead
        }
        
        // recursive
        func reverseList_Rec(_ head: ListNode?) -> ListNode? {
            if head?.next == nil {
                return head
            }
            
            let nextNode = head?.next;
            let newHead = reverseList_Rec(nextNode)
            nextNode?.next = head
            head?.next = nil
            
            return newHead
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.