Insert node before (kth node) in DLL

Linked-List Fundamentals (Doubly LL) Easy

Given the head of a doubly linked list and two integers X and K, insert a new node with value X, before the Kth node of the linked list and return the head of the modified linked list.

Examples:

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

Output: head -> 1 <-> 7 <-> 3 <-> 5

Explanation: A node with value 7 was added before the 2nd node.

Input: head -> 5, X = 7, K = 1

Output: head -> 7 <-> 5

Explanation: A node with value 7 was added, note that the head was changed.

Input: head -> 4 <-> 5, X = 10, K = 2

Constraints

  • n == Number of nodes in the linked list
  • 1 <= n <= 100
  • 0 <= ListNode.val <= 100
  • 0 <= X <= 100
  • 1 <= K <= n

Hints

  • If the list is empty (head = NULL), insert X as the only node. If K = 1, insert X before the first node, making it the new head. If K is greater than the number of nodes, insert at the end.
  • Use a pointer to move K-1 steps to locate the (K-1)th node. If K exceeds the length, insert at the end. Update prev and next pointers of adjacent nodes.

Company Tags

Splunk Zoho Intel JPMorgan Chase Philips Healthcare Etsy Square Shopify Visa Mastercard Instacart Medtronic HashiCorp Electronic Arts PayPal Uber Deloitte NVIDIA Robinhood Roblox Target Boston Consulting Group Johnson & Johnson Rakuten Siemens Healthineers TCS Cognizant Accenture Infosys Capgemini Wipro