Reverse Linked List

Try to solve the Reverse Linked List problem.

Statement#

Given the head of a singly linked list, reverse the linked list and return its updated head.

Constraints:

Let n be the number of nodes in a linked list.

  • 11 \leq n 500\leq 500
  • 5000-5000 \leq Node.value 5000\leq 5000

Examples#

Created with Fabric.js 3.6.6 Input 7 8 6 6 8 7 Output Sample example 1

1 of 5

Created with Fabric.js 3.6.6 9 0 8 2 Input 2 8 0 9 Output Sample example 2

2 of 5

Created with Fabric.js 3.6.6 Input 1 2 3 4 5 5 4 3 2 1 Output Sample example 3

3 of 5

Created with Fabric.js 3.6.6 Input 8 5 1 6 4 7 7 4 6 1 5 8 Output Sample example 4

4 of 5

Created with Fabric.js 3.6.6 Input Output 0 8 3 1 9 2 7 7 2 9 1 3 8 0 Sample example 5

5 of 5

Understand the problem#

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

1

What is the output if the following linked list is provided as input?

4 → 2 → 7 → 8 → 9 → 0 → 2

A)

9 → 0 → 2 → 8 → 4 → 2 → 7

B)

7 → 2 → 4 → 8 → 2 → 0 → 9

C)

2 → 0 → 9 → 8 → 7 → 2 → 4

D)

0 → 2 → 2 → 4 → 8 → 9

Question 1 of 40 attempted

Figure it out!#

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Drag and drop the cards to rearrange them in the correct sequence.

Initialize the prev and next pointers to NULL and set the current pointer to the head node.

Traverse the linked list until the current pointer reaches the end of the list.

Within the loop, set the next pointer to the next node in the list and reverse the current node’s pointer to point to the previous node.

Update the prev and curr pointers.

After the loop, the prev pointer will point to the last node of the original linked list, so set the head pointer to the prev pointer.


Try it yourself#

Implement your solution in main.py in the following coding playground. You’ll need the provided supporting code to implement your solution.

Python
main.py
linked_list_node.py
linked_list.py
Input #1
%0 node_01 1 node_11 -2 node_01->node_11 node_21 3 node_11->node_21 node_31 4 node_21->node_31 node_41 -5 node_31->node_41 node_51 4 node_41->node_51 node_61 3 node_51->node_61 node_71 -2 node_61->node_71 node_81 1 node_71->node_81
Visualization for Input #1
Reverse Linked List

In-place Reversal of a Linked List: Introduction

Solution: Reverse Linked List