🐹双指针
前面添加一个哑节点,可以避免头节点的特殊处理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* nou = new ListNode(0); nou->next = head; auto slow = nou; auto quick = nou; ++n; while(n--) quick = quick->next; while(quick) { slow = slow->next; quick = quick->next; } auto nx = slow->next->next; slow->next = nx; return nou->next; } };
|
Accepted
208/208 cases passed (4 ms)
Your runtime beats 92.07 % of cpp submissions
Your memory usage beats 11.12 % of cpp submissions (8.6 MB)
🐶格外空间
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { vector<ListNode*> nodes; auto h = head; while(h) { nodes.push_back(h); h = h->next; } int pos = nodes.size() - n; if(pos - 1 < 0) return head->next; nodes[pos - 1]->next = pos + 1 >= nodes.size() ? nullptr : nodes[pos + 1]; return head; } };
|
Accepted
208/208 cases passed (4 ms)
Your runtime beats 92.07 % of cpp submissions
Your memory usage beats 5.22 % of cpp submissions (8.8 MB)