diff --git a/19_remove_nth_node_from_end_of_list/main.cpp b/19_remove_nth_node_from_end_of_list/main.cpp new file mode 100644 index 0000000..91e15ca --- /dev/null +++ b/19_remove_nth_node_from_end_of_list/main.cpp @@ -0,0 +1,35 @@ +#include +using namespace std; + +struct ListNode { + int val; + ListNode* next; + ListNode() : val(0), next(nullptr) {} + ListNode(int x) : val(x), next(nullptr) {} + ListNode(int x, ListNode* next) : val(x), next(next) {} +}; + +class Solution { + public: + ListNode* removeNthFromEnd(ListNode* head, int n) { + vector pointerTable; + int sz = 0; + + ListNode* currentNode = head; + while (currentNode != nullptr) { + sz++; + pointerTable.push_back(currentNode); + currentNode = currentNode->next; + } + + if (sz == 1) return nullptr; + if (sz - n - 1 < 0) return head->next; + + currentNode = pointerTable[pointerTable.size() - n - 1]; + ListNode* target = currentNode->next; + currentNode->next = currentNode->next->next; + delete target; + + return head; + } +};