iOS Interview - Leetcode 206. Reverse Linked List

May 26, 20242 min read#swift, #interview, #leetcode

Leetcode: 206. Reverse Linked List

  • Primary idea: Iterate over the list, reverse the nodes and return the new head node.
  • Time Complexity: O(n)
  • Space Complexity: O(1)
public class ListNode {
    public var val: Int
    public var next: ListNode?
    public init(_ val: Int) {
        self.val = val
        self.next = nil
    }

    public func print() {
        var node: ListNode? = self
        var result = ""
        while node != nil {
            result += "\(node!.val)"
            node = node?.next
            if node != nil {
                result += " -> "
            }
        }
        Swift.print(result)
    }
}

func reverseList(_ head: ListNode?) -> ListNode? {
      // Check if the list has more than 1 element
      guard let head = head, let next = head.next else {
          return head
      }

      // Reverse the nodes in the list
      let node = reverseList(next)

      // Set the old head to be the new tail
      next.next = head
      head.next = nil

      return node
  }

  /// Iterate over the list, reverse the nodes and return the new head node.
  private func reverseList(head: ListNode?) -> ListNode? {

      var tempNode: ListNode?
      var firstNode = head

      while firstNode != nil {
          let secondNode = firstNode!.next
          firstNode!.next = tempNode
          tempNode = firstNode
          firstNode = secondNode
      }

      return tempNode
  }

var listNode1 = ListNode(1)
listNode1.next = ListNode(2)
reverseList(listNode1)?.print() // 2 -> 1

var listNode2 = ListNode(1)
listNode2.next = ListNode(2)
listNode2.next?.next = ListNode(3)
listNode2.next?.next?.next = ListNode(4)
listNode2.next?.next?.next?.next = ListNode(5)
reverseList(listNode2)?.print() // 5 -> 4 -> 3 -> 2 -> 1
Quick Drop logo

Profile picture

Personal blog by An Tran. I'm focusing on creating useful apps.
#Swift #Kotlin #Mobile #MachineLearning #Minimalist


© An Tran - 2024