Insertion before the value X in LL

Linked-List Fundamentals (Single LL) Easy

Given the head of a singly linked list and two integers X and val, insert a node with value val before the node with value X in the linked list and return the head of the modified list.

Examples:

Input: head -> 1 -> 2 -> 3, X = 2, val = 5

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

Explanation: The node with value 5 was added before the node with value 2

Input: head -> 1 -> 2 -> 3, X = 7, val = 5

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

Explanation: No node was added as X was not found in the list.

Input: head -> 1, X = 1, val = 10

Constraints

  • n == number of nodes in the Linked List
  • 1 <= n <= 1000
  • 0 <= ListNode.val <= 100
  • 0 <= X <= 100
  • 0 <= val <= 100
  • Number of nodes with value X is 0 or 1

Hints

  • Traverse the list from the head to locate the first node with value X.
  • If X is found at the head, the task becomes straightforward, create a new node and make it the new head. For all other positions, keep track of the node preceding X during traversal, as this is where the insertion will occur.

Company Tags

Rakuten JPMorgan Chase HCL Technologies Visa DoorDash Cerner MongoDB OYO Rooms Zomato Pinterest GE Healthcare Ubisoft Square Epic Games Mastercard Bain & Company Byju's Western Digital Optum PayPal Broadcom Micron Technology Seagate Technology Unity Technologies Swiggy TCS Cognizant Accenture Infosys Capgemini Wipro