Given a linked list, the task is to remove the last node of the linked list and update the head pointer of the linked list.
Input: 1 -> 2 -> 3 -> 4 -> 5 -> NULL Output: 1 -> 2 -> 3 -> 4 -> NULL Explanation: The last node of the linked list is 5, so 5 is deleted. Input: 2 -> 4 -> 6 -> 8 -> 33 -> 67 -> NULL Output: 2 -> 4 -> 6 -> 8 -> 33 -> NULL Explanation: The last node of the linked list is 67, so 67 is deleted.
Approach: To delete the last node of a linked list, find the second last node and make the next pointer of that node null.
- If the first node is null or there is only one node, then return null
if headNode == null then return null if headNode.nextNode == null then free head and return null
- Create an extra space secondLast, and traverse the linked list till the second last node.
while secondLast.nextNode.nextNode != null secondLast = secondLast.nextNode
- delete the last node, i.e. the next node of second last node delete(secondLast.nextNode),and set the value of next of second last node to null.
8 23 11 29
- Time Complexity: O(n).
The algorithm involves traversal of the linked list till its end, So the time complexity required is O(n).
- Space Complexity: O(1).
No extra space is required, so the space complexity is constant
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- Remove first node of the linked list
- Remove Nth node from end of the Linked List
- Remove every k-th node of the linked list
- Create new linked list from two given linked list with greater element at each node
- Swap Kth node from beginning with Kth node from end in a Doubly Linked List
- Swap Kth node from beginning with Kth node from end in a Linked List
- Remove duplicates from a sorted linked list
- Remove duplicates from an unsorted linked list
- Detect and Remove Loop in a Linked List
- Program to remove vowels from Linked List
- Remove duplicates from a sorted doubly linked list
- Remove all special characters from a singly Linked List
- Remove all the Even Digit Sum Nodes from a Doubly Linked List
- Remove duplicates from an unsorted doubly linked list
- Remove duplicates from a sorted linked list using recursion
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.