DevPath

← All problems

Reverse a Linked List

Easy linked-list · two-pointers

Description

Return the values of the list in reverse order.

Constraints

0 <= n <= 100000

Examples

Input: list = [1,2,3,4,5]

Output: [5,4,3,2,1]

Hints (1)
  • Walk the list with a previous pointer, rewriting each next link.

Solutions

Iterative pointer reversal. · Time O(n) · Space O(1)

func reverseList(list []int) []int {
    out := make([]int, len(list))
    for i, v := range list {
        out[len(list)-1-i] = v
    }
    return out
}

Create a free account to submit solutions, track progress and save problems.

Create account