我的Bilibili频道:香芋派Taro
我的个人博客:taropie0224.github.io(阅读体验更佳)
我的公众号:香芋派的烘焙坊
我的音频技术交流群:1136403177
我的个人微信:JazzyTaroPie
https://leetcode.cn/problems/remove-nth-node-from-end-of-list/
题解and思路
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { if (head == nullptr) return head; vector<int> vec; ListNode* node = head; while (node != nullptr) { vec.push_back(node->val); node = node->next; } int len = vec.size(); if (len == 1) { return nullptr; } vec.erase(vec.begin() + len - n); node = head; for (int i = 0; i < vec.size(); i++) { node->val = vec[i]; if (i == vec.size() - 1) { node->next = nullptr; } else { node = node->next; } } return head; } };
|