941. Insertion at the head of Linked List

Given the head of a singly linked list and an integer X, insert a node with value X at the head of the linked list and return the head of the modified list.

Example 1:

Input: linkedList = [1, 2, 3], X = 7

Output: [7, 1, 2, 3]

Explanation:

7 was added as the 1st node.

Example 2:

Input: linkedList = [], X = 7

Output: [7]

Explanation:

7 was added as the 1st node.

Now Your Turn!

Pick the correct output for the given input

Input: [1, 3], X = 4

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 <= 1000
  • 0 <= ListNode.val <= 100
  • 0 <= X <= 100

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
/*
Definition of singly linked list:
class ListNode{
public:
int data;
ListNode *next;
ListNode() : data(0), next(nullptr) {}
ListNode(int x) : data(x), next(nullptr) {}
ListNode(int x, ListNode *next) : data(x), next(next) {}
};
*/
 
class Solution {
public:
ListNode* insertAtHead(ListNode* &head, int X) {
//your code goes here
}
};
Test Case

Input:

X
Linked List