/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reverseList(head *ListNode) *ListNode {
curr := head
var prev *ListNode = nil
var next *ListNode = nil
for curr != nil {
next = curr.Next
curr.Next = prev
prev = curr
curr = next
}
head = prev
return head
}
-
Keep track of 3 pointer,
prev
,curr
andnext
. Withcurr
being initialised tohead
and the others beingnil
. -
Move through
curr
till we reach the end of linked list. -
Set
next
ascurr.Next
. Now the current node's pointer can be set to the previous node. -
After updating the current node's pointer, move
curr
tonext
andprev
tocurr
. -
Finally, set the new
head
asprev
, this will update the head to the new beginning of the list.