/** * Definition for singly-linked list. * public class ListNode { * public var val: Int * public var next: ListNode? * public init() { self.val = 0; self.next = nil; } * public init(_ val: Int) { self.val = val; self.next = nil; } * public init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next; } * } */ classSolution{ funcreverseList(_head: ListNode?) -> ListNode? { var mutHead = head if mutHead ==nil|| mutHead?.next ==nil { return mutHead } // initialize three pointers // prev as NULL, curr as head, next as NULL var prev: ListNode? var curr = head var next: ListNode? // iterate through the link list, in the loop do the following while (curr !=nil) { // Before changing next of current // store the next node next = curr?.next // Now change next of current // This is where revering happens curr?.next = prev // Move the prev and curr one step ahead prev = curr curr = next } return prev } }