3. Reverse a LL

Given the head of a singly linked list. Reverse the given linked list and return the head of the modified list.

Example 1:

Input: head -> 1 -> 2 -> 3 -> 4 -> 5

Output: head -> 5 -> 4 -> 3 -> 2 -> 1

Explanation: All the links are reversed and the head now points to the last node of the original list.

Example 2:

Input: head -> 6 -> 8

Output: head -> 8 -> 6

Explanation: All the links are reversed and the head now points to the last node of the original list.

This can be seen like: 6 <- 8 <- head.

Now Your Turn!

Pick the correct output for the given input

Input: head -> 1

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 0 <= number of nodes in the Linked List <= 105
  • 0 <= ListNode.val <= 104

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
/*
Definition of singly linked list:
struct ListNode
{
int val;
ListNode *next;
ListNode()
{
val = 0;
next = NULL;
}
ListNode(int data1)
{
val = data1;
next = NULL;
}
ListNode(int data1, ListNode *next1)
{
val = data1;
next = next1;
}
};
*/
 
class Solution {
public:
ListNode* reverseList(ListNode* head) {
}
};
Test Case

Input:

Nums