RSS Amplifier

Swift by An Tran · May 26, 2024

iOS Interview - Leetcode 206. Reverse Linked List

0
Sign in to vote or save

This page did not load. You can still read it on the original site — the toolbar below keeps your place in the directory.

Leetcode: 206. Reverse Linked List Primary idea: Iterate over the list, reverse the nodes and return the new head node. Time Complexity: O(n…

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

Read on antran.app

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.