![]() |
VOOZH | about |
Given a Doubly Linked List, insert a new node at the end of the linked list.
Examples:
Input: Linked List = 1 <-> 2 <-> 3, NewNode = 4
Output: 1 <-> 2 <-> 3 <-> 4Input: Linked List = NULL, NewNode = 1
Output: 1
Approach:
Inserting at the end involves traversing the entire list until we reach the last node. We then set the last node’s next reference to point to the new node and new node's previous reference to point to the last node. Thus, making the new node the last element in the list.
Steps to insert a new node at the end:
1 <-> 2 <-> 3 <-> 4
Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(1)