← TopicsLinked List · 1/18

Reverse a Linked List

Given the head of a singly linked list, reverse the list and return the new head. Reversal must be done in place by re-pointing each node's Next pointer; do not allocate a new list of nodes. Input is a batch. Line 1 is the count T. Each of the next T lines describes one list: an integer n (the list length) followed by n integers (the node values in head-to-tail order). A line of just "0" denotes an empty list. For each case, output the values of the reversed list as space-separated integers on one line (an empty list yields an empty line).

func reverseList(head *ListNode) *ListNode {
var prev *ListNode
curr := head
next := curr.Next
prev = curr
curr = next
}
return prev
}

this session — 0 attempt(s), 0 passed, 0 failed. (ephemeral; discarded when you leave)