Remove last node of the linked list
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. Show Examples: 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.Recommended: Please try your approach on {IDE} first, before moving on to the solution. Approach: To delete the last node of a linked list, find the second last node and make the next pointer of that node null. Algorithm: 1. If the first node is null or there is only one node, then they return null. if headNode == null then return null if headNode.nextNode == null then free head and return null2. Create an extra space secondLast, and traverse the linked list till the second last node. while secondLast.nextNode.nextNode != null secondLast = secondLast.nextNode3. delete the last node, i.e. the next node of the second last node delete(secondLast.nextNode), and set the value of the next second-last node to null. Implementation: C++
Java
Python3
C#
Javascript
Output: 8 23 11 29 Complexity Analysis:
Article Tags : Data Structures Linked List Technical Scripter Technical Scripter 2018 Practice Tags : Data Structures Linked List Deletion in singly linked list at the endThere are two scenarios in which, a node is deleted from the end of the linked list.
C Exercises: Delete the last node of Singly Linked ListLast update on December 20 2021 09:10:22 (UTC/GMT +8 hours)Logic to Delete the Last Node of a Linked List
Read also: Delete any node from a linked list. Read also: Delete the first node of a linked list. |