Deletion of the tail of LL

Linked-List Fundamentals (Single LL) Easy

Given the head of a singly linked list, delete 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

Output: head -> 1 -> 2

Explanation: The last node was removed.

Input: head -> 1

Output: head

Explanation: Note that the value of head is null here.

Input: head -> 7 -> 8

Constraints

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

Hints

  • If the list is empty (head == None), return None. If there is only one node (head.next == None), removing the tail leaves an empty list, so return None.
  • Traverse to the last node (tail), which is the node where next == None. Update the second last node’s next = None to remove the tail. Return the updated head of the list.

Company Tags

McKinsey & Company ARM Oracle Bloomberg Goldman Sachs Salesforce Texas Instruments IBM Databricks Riot Games Ubisoft Stripe PwC Red Hat Flipkart DoorDash NVIDIA JPMorgan Chase Philips Healthcare Micron Technology Dropbox Broadcom Airbnb Western Digital Johnson & Johnson TCS Cognizant Accenture Infosys Capgemini Wipro