Delete a node in a Doubly Linked ListPre-requisite: Doubly Link List Set 1| Introduction and Insertion Show Write a function to delete a given node in a doubly-linked list. Remove last node of the linked listGiven a linked list, the task is to remove the last node of the linked list and update the head pointer of the linked list. 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 Introduction to Singly Linked ListSingly Linked List is a variant of Linked List which allows only forward traversal of linked lists. This is a simple form, yet it is effective for several problems such as Big Integer calculations. A singly linked list is made up of nodes where each node has two parts:
The beginning of the node marked by a special pointer named START. The pointer points to the fist node of the list but the link part of the last node has no next node to point to. The main difference from an array is:
In Singly Linked List, only the pointer to the first node is stored. The other nodes are accessed one by one. To get the address of ith node, we need to traverse all nodes before it because the address of ith node is stored with i-1th node and so on. Singly Linked List vs Doubly Linked ListBefore looking at the differences between the singly linked list and doubly linked list, we first understand what is singly linked list and doubly linked list separately. |