Insertion at the head of LL

Linked-List Fundamentals (Single LL) Easy

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


The head is the first node of the linked list.

Examples:

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

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

Explanation: 7 was added as the 1st node.

Input: head, X = 7

Output: head -> 7

Explanation: 7 was added as the 1st node.

Input: head -> 1 -> 3, X = 4

Constraints

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

Hints

  • Create a new node with value X. Set the next pointer of the new node to the current head.
  • Update the head pointer to point to the new node, making it the first node of the list.

Company Tags

DoorDash Oracle Twilio Seagate Technology Shopify Cerner Qualcomm Teladoc Health Riot Games Roche Databricks JPMorgan Chase Johnson & Johnson MongoDB Goldman Sachs Flipkart Siemens Healthineers Byju's Docker Rakuten HashiCorp Chewy ARM Zynga Optum TCS Cognizant Accenture Infosys Capgemini Wipro