Insert node before tail 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 tail of the linked list and return the head of the modified list.

Examples:

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

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

Explanation: 3 was added before the last node.

Input: head -> 4, X = 6

Output: head -> 6 <-> 4

Explanation: 6 was added before 4, note that the head was changed as a result.

Input: head -> 4 <-> 5, X = 6

Constraints

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

Hints

  • If the list is empty (head = NULL), insert X as the only node. If the list has only one node, insert X before the existing node (making X the new head). If the list has at least two nodes, traverse to tail’s previous node and insert X before the tail.
  • Traverse to the second-last node. Insert X by adjusting prev and next pointers."

Company Tags

DoorDash Flipkart Activision Blizzard Mastercard Broadcom Texas Instruments Bungie GE Healthcare Docker Zynga Qualcomm Alibaba Red Hat Instacart Intel Roche NVIDIA Twilio Robinhood Morgan Stanley AMD Electronic Arts Airbnb Byju's Oracle TCS Cognizant Accenture Infosys Capgemini Wipro