Insertion at the tail 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 tail of the linked list and return the head of the modified list.


The tail is the last node of the linked list.

Examples:

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

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

Explanation: 7 was added as the last node.

Input: head, X = 0

Output: head -> 0

Explanation: 0 was added as the last/only node.

Input: head -> 5 -> 6, X = 8

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 and set its next pointer to None. If the list is empty (head is None), the new node becomes the head of the list. Otherwise, traverse the list to reach the current tail (node whose next pointer is None).
  • Use a pointer to traverse the list starting from the head. Stop when the pointer reaches the tail node (where next is None). Update the next pointer of the tail node to point to the new node.

Company Tags

GE Healthcare Square Teladoc Health Flipkart Pinterest Texas Instruments Nutanix Robinhood Western Digital Medtronic Siemens Healthineers Roche Bloomberg KPMG OYO Rooms Twilio Target Mastercard DoorDash Deloitte Epic Games Databricks Walmart PwC Uber TCS Cognizant Accenture Infosys Capgemini Wipro