Delete Nth node from the end of the given linked listGiven a linked list and an integer N, the task is to delete the Nth node from the end of the given linked list. Show Examples:
Recommended: Please try your approach on {IDE} first, before moving on to the solution. Intuition: Lets K be the total nodes in the linked list. Observation : The Nthnode from the end is (K-N+1)th node from the beginning. So the problem simplifies down to that we have to find (K-N+1)th node from the beginning.
Approach:
Below is the implementation of the above approach: C++
Java
Python3
C#
Javascript
Output
Created Linked list is:
2 3 1 7
Linked List after Deletion is:
2 3 1
we already covered the iterative version above, Recursive Approach : C++
Output
1 2 3 4 5
1 2 3 5
1
Empty Linked List
1 2
1
Two Pointer Approach – Slow and Fast Pointers This problem can be solved by using two pointer approach as below:
Python
Output
***** Linked List Before deletion *****
1
2
3
4
5
************** Delete nth Node from the End *****
*********** Linked List after Deletion *****
1
2
3
5
Time complexity: O(n)
Article Tags :
Linked List
Delete a Linked List Traversal Practice Tags :
Linked List Traversal Remove Nth node from end of the Linked ListGiven a linked list. The task is to remove the Nth node from the end of the linked list. Examples:
Recommended: Please try your approach on {IDE} first, before moving on to the solution. Prerequisites:
C
C++
Java
Python3
C#
Javascript
Output
Linked list before modification:
1 2 3 4 5
Linked list after modification:
1 2 3 5
Another Approach: Two Pointer Approach
C++
Output
Linked list before modification:
1 2 3 4 5
Linked list after modification:
1 2 3 5
Article Tags :
Linked List Mathematical
Traversal Practice Tags :
Linked List Mathematical Traversal LeetCode #19 - Remove Nth Node From End Of ListHello LeetCode enthusiasts 👋! It’s time to look the nineteenth problem from LeetCode.
|