Insert node before head in DLL

Linked-List Fundamentals (Doubly LL) Easy

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

Examples:

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

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

Explanation: 3 was added before the 1st node. Note that the head's value is changed.

Input: head -> 5, X = 7

Output: head -> 7 <-> 5

Input: head -> 2 <-> 3, X = 10

Constraints

  • n == Number of nodes in the Linked List
  • 1 <= n <= 100
  • 0 <= ListNode.val <= 100
  • 0 <= X <= 100

Hints

  • Create a new node with value X. Set the new node’s next pointer to the current head. Update the head’s prev pointer to point to the new node
  • Update head = new_node to reflect the new head.

Company Tags

Goldman Sachs Electronic Arts Riot Games eBay Dropbox KPMG Reddit Lyft HCL Technologies Zynga Roche Walmart Red Hat Cerner Siemens Healthineers Target Snowflake PwC Ubisoft Morgan Stanley Rakuten Activision Blizzard PayPal Bungie Broadcom TCS Cognizant Accenture Infosys Capgemini Wipro