FastPrepReverse a Linked List

Reverse a Linked List

IBM logoIBM● EasyFULLTIMEPHONE SCREEN

Problem statement

Given the head of a singly linked list, reverse the order of its nodes and return the new head.

The input list is finite and has no cycle. An empty list is represented by []; return an empty list for that input.

For example, the list [2, 5, 8] becomes [8, 5, 2]. Duplicate and negative values remain unchanged.

Function

reverseList(head: ListNode) → ListNode

Examples

Example 1

head = [2,5,8]return = [8,5,2]

The last node becomes the head. Following the reversed links visits 8, then 5, then 2.

Example 2

head = []return = []

There are no nodes to reverse, so the result is an empty list.

Constraints

  • The list contains between 0 and 5000 nodes.
  • Each node value is between -5000 and 5000, inclusive.
  • The input is a finite, acyclic singly linked list.

More IBM problems

See IBM hiring insights
Saved
public ListNode reverseList(ListNode head) {
    // write your code here
}
head[2,5,8]
expected[8,5,2]
Checking account…