From 407834c369b0bd294c4ff52f69097666e935fbd8 Mon Sep 17 00:00:00 2001 From: Zahra Shahid Date: Sun, 2 Oct 2022 22:58:27 +0500 Subject: [PATCH] Added a solution to Question 42 of Leetcode --- .../Q42_RemoveNthNodeFromEndOfList.cpp | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 leetCode Solutions/Q42_RemoveNthNodeFromEndOfList/Q42_RemoveNthNodeFromEndOfList.cpp diff --git a/leetCode Solutions/Q42_RemoveNthNodeFromEndOfList/Q42_RemoveNthNodeFromEndOfList.cpp b/leetCode Solutions/Q42_RemoveNthNodeFromEndOfList/Q42_RemoveNthNodeFromEndOfList.cpp new file mode 100644 index 0000000..a561b75 --- /dev/null +++ b/leetCode Solutions/Q42_RemoveNthNodeFromEndOfList/Q42_RemoveNthNodeFromEndOfList.cpp @@ -0,0 +1,26 @@ +/* +This algo uses the curr pointer to loop over the linkedlist and store its total length in a variable. +If the node required to remove resides at the end of the list, its removed and returned. +Else, the curr pointer loops over the list again for the (length-requiredNodeNumberfromLast) to remove the desired Node +*/ + + +class Solution { +public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + int length = 0; + ListNode* curr = head; + while(curr){ + length++; + curr=curr->next; + } + if(length == n) return head->next; + curr = head; + for(int i = 1; i < length-n; i++){ + curr = curr->next; + } + curr->next = curr->next->next; + return head; + + } +}; \ No newline at end of file