Insert Node Between Two Nodes

TCS NQT Coding Easy Go Ad-Free - ₹20/mo

Given the head of a singly linked list, and two integers `a` and `b` representing the data of two consecutive nodes in the list, and an integer `x`, insert a new node with data `x` between the nodes with data `a` and `b`. It is guaranteed that nodes with data `a` and `b` exist and are adjacent. Return the head of the modified linked list.

Examples:

Input: head = [1, 2, 3, 4], a = 2, b = 3, x = 5

Output: [1, 2, 5, 3, 4]

Input: head = [10, 20, 30], a = 10, b = 20, x = 15

Output: [10, 15, 20, 30]

Input: head = [1, 2], a = 1, b = 2, x = 3

Output: [1, 3, 2]

Constraints

  • The number of nodes in the linked list is between 1 and 10^5.
  • Node values are integers in the range [-10^9, 10^9].
  • a and b are guaranteed to be present in the list and consecutive.
  • x is an integer.