Delete the element with value X

Linked-List Fundamentals (Single LL) Easy

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

Examples:

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

Output: head -> 3 -> 4

Explanation: The node with value 5 was removed.

Input: head -> 3 -> 4 -> 5, X = 7

Output: head -> 3 -> 4 -> 5

Explanation: No nodes were removed.

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

Constraints

  • n == number of nodes in the Linked list
  • 1 <= n <= 1000
  • 0 <= ListNode.val <= 100
  • 0 <= X <= 100
  • Number of nodes with value X is either 0 or 1

Hints

  • If the list is empty (head is None), return None as there is no node to delete. If the value X is present in the head node, update the head pointer to head.next to remove the head node. Traverse the list starting from the head, keeping track of the previous node
  • Use a pointer to traverse the list starting from the head. Maintain a reference to the current node and the previous node during traversal.

Company Tags

AMD Johnson & Johnson Unity Technologies Roblox Riot Games Zomato Swiggy Bloomberg Reddit McKinsey & Company DoorDash Seagate Technology Texas Instruments Qualcomm Western Digital PwC Salesforce Dropbox OYO Rooms Cerner Walmart Robinhood Electronic Arts Pinterest Goldman Sachs TCS Cognizant Accenture Infosys Capgemini Wipro