Problem · Linked List

Reverse a Singly Linked List

Learn this problem
EasyMicrosoft logoMicrosoftNEW GRADONSITE INTERVIEW
See Microsoft hiring insights

Problem statement

Given the head head of a singly linked list, reverse every next pointer and return the new head.

The returned list must contain exactly the original nodes and values in reverse order. Return null when head is null.

Function

reverseList(head: ListNode) → ListNode

Examples

Example 1

head = [1,2,3,4,5]return = [5,4,3,2,1]

Every link is reversed, making 5 the new head and 1 the new tail.

Example 2

head = []return = []

A null head remains null.

Example 3

head = [7]return = [7]

A one-node list is already reversed.

Constraints

  • 0 <= number of nodes <= 10^5
  • -10^9 <= node.val <= 10^9
  • The input list is finite and acyclic.

More Microsoft problems

drafts saved locally
/**
 * Definition for singly-linked list.
 * class ListNode {
 *   int val;
 *   ListNode next;
 * }
 */
public ListNode reverseList(ListNode head) {
  // write your code here
}
head[1,2,3,4,5]
expected[5,4,3,2,1]
checking account