Remove Nth Node From End of List Solution
Remove Nth Node From End Of List:
Given the head
of a linked list, remove the nth
node from the end of the list and return its head.
Two Sum Leetcode Solution :
Constraints :
- The number of nodes in the list is sz.
- 1 <= sz <= 30
- 0 <= Node.val <= 100
- 1 <= n <= sz
Example 1:
Input: head = [1], n = 1
Output: [ ]
Example 2:
Input: head = [1,2], n = 1
Output: [1]
In the above problem, you are given the head of the linked list. The goal is to remove nth node from the end of the list and return it’s head.
Constraints:
- The number of nodes in the list is sz.
- 1 <= sz <= 30
- 0 <= Node.val <= 100
- 1 <= n <= sz
Approach :
Using Two Pointer’s Approach. (slow & fast)
first make the distance between slow and fast by moving fast,while(n–){
fast=fast->next;}then, move slow and fast pointer one by one until
while(fast->next != NULL){
slow=slow->next;
fast=fast->next;
}and in last :-
slow->next = slow->next->next;
return head;but there is an edge case:
if my n = n.size() , in this my fast will point out to NULL
so in we return slow->next;
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Code :
class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode *slow=head,*fast=head; while(n--){ fast=fast->next; } if(fast==NULL){ return slow->next; } while(fast->next != NULL){ slow=slow->next; fast=fast->next; } slow->next = slow->next->next; return head; } };
class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { if(head == null) return head; int k = 0; ListNode curr = head; for(; curr != null; curr = curr.next) k++; k -= n; //to get position of given element from first node if(k == 0) return head.next; for(curr = head; k > 1; k--, curr = curr.next) ; curr.next = curr.next.next; // to remove that node return head; } }
class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: fast, slow = head, head for _ in range(n): fast = fast.next if not fast: return head.next while fast.next: fast, slow = fast.next, slow.next slow.next = slow.next.next return head
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment