# 19. Remove Nth Node From End of List Difficulty: Medium ## Solution ```cpp= /** *** Author: R-CO *** E-mail: daniel1820kobe@gmail.com *** Date: 2020-09-01 **/ #include <cstdlib> #include <iostream> #include <vector> using namespace std; /** * Definition for singly-linked list. * 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) {} * }; */ 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<ListNode*> vec; ListNode* ptr = head; while (ptr != nullptr) { vec.emplace_back(ptr); ptr = ptr->next; } int index = static_cast<int>(vec.size()) - n; if (index > 0) { vec[index - 1]->next = vec[index]->next; } else { head = head->next; } return head; } }; void DisplayList(ListNode* head) { while (head != nullptr) { cout << head->val << " "; head = head->next; } } void ReleaseList(ListNode* head) { while (head != nullptr) { auto ptr = head; head = head->next; delete ptr; } } int main(int argc, char* argv[]) { /* */ auto head = new ListNode(1); auto ptr = head; for (int i = 2; i <= 5; ++i) { ptr->next = new ListNode(i); ptr = ptr->next; } DisplayList(head); cout << endl; Solution solution; head = solution.removeNthFromEnd(head, 5); DisplayList(head); cout << endl; ReleaseList(head); return EXIT_SUCCESS; } ``` ## Result Success Details Runtime: 4 ms, faster than 83.97% of C++ online submissions for Remove Nth Node From End of List. Memory Usage: 10.7 MB, less than 8.08% of C++ online submissions for Remove Nth Node From End of List. ###### tags: `LeetCode-Medium` `C++`