Reverse a Linked List: Swift - COFPROG

Reverse a Linked List: Swift

Swift: Solving the "Reverse a Linked List" Problem

Problem: Reverse a Linked List

Given the head of a singly linked list, reverse the list and return the reversed list.

Example:

Input: head = [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]
        

Swift Solution

class ListNode {
    var val: Int
    var next: ListNode?

    init(_ val: Int) {
        self.val = val
        self.next = nil
    }
}

class Solution {
    func reverseList(_ head: ListNode?) -> ListNode? {
        var prev: ListNode? = nil
        var current = head

        while current != nil {
            let nextTemp = current!.next
            current!.next = prev
            prev = current
            current = nextTemp
        }
        
        return prev
    }
}

// Helper function to print the list
func printList(_ head: ListNode?) {
    var node = head
    while node != nil {
        print(node!.val, terminator: " ")
        node = node!.next
    }
}

// Example usage
let head = ListNode(1)
head.next = ListNode(2)
head.next?.next = ListNode(3)
head.next?.next?.next = ListNode(4)
head.next?.next?.next?.next = ListNode(5)

let solution = Solution()
let reversedHead = solution.reverseList(head)
printList(reversedHead) // Output: 5 4 3 2 1
        

Explanation

In this solution, we use three pointers: prev, current, and nextTemp. As we traverse the list, we reverse the direction of each node by pointing it to the previous node. By the end of the traversal, prev will point to the new head of the reversed list.

Latest
Previous
Next Post »

BOOK OF THE DAY