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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Create new linked list from two given linked list with greater element at each node
- Find the second last node of a linked list in single traversal
- Remove every k-th node of the linked list
- Remove first node of the linked list
- Remove Nth node from end of the Linked List
- Swap Kth node from beginning with Kth node from end in a Linked List
- Swap Kth node from beginning with Kth node from end in a Doubly Linked List
- Insert a node in Linked List before a given node
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Merge a linked list into another linked list at alternate positions
- Check if a linked list is Circular Linked List
- Convert singly linked list into circular linked list
- Difference between Singly linked list and Doubly linked list
- Convert Singly Linked List to XOR Linked List
- Move last element to front of a given Linked List
- Delete last occurrence of an item from linked list
- Find the sum of last n nodes of the given Linked List
- Exchange first and last nodes in Circular Linked List
- Rearrange a linked list in to alternate first and last element
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.