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
}