954. Insertion at the Kth position of Linked List

Given the head of a singly linked list and two integers X and K, insert a node with value X as the kth node of the linked list and return the head of the modified list.

Example 1:

Input: linkedList = [1, 2, 3], X = 5, K = 2

Output: [1, 5, 2, 3]

Example 2:

Input: linkedList = [], X = 7, K = 1

Output: [7]

Explanation:

Note that the value of the head was changed.

Now Your Turn!

Pick the correct output for the given input

Input: linkedList = [1, 2], X = 15, K = 3

Still unsure what the problem is asking ?

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

Constraints:

  • n == number of nodes in the Linked List
  • 0 <= n <= 1000
  • 0 <= ListNode.val <= 100
  • 0 <= X <= 100
  • 1 <= K <= n+1

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* insertAtKthPosition(ListNode* &head, int X, int K) {
//your code goes here
}
};
Test Case

Input:

K
X
Linked List