Reverse Linked List


#1

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?


#2

Reversing the chain using two pointers. Below solution runs in 0 ms in Golang.

func reverseList(head *ListNode) *ListNode {
    p1 := &ListNode{}
    var p2 *ListNode
    p2 = nil
    for head != nil{
        p1 = head.Next
        head.Next = p2
        p2 = head
        head = p1
    }
    
    return p2
}