思想:用内存换时间
为了不二次遍历,在第一次遍历的时候用指针数组 vector<ListNode*>p; 将每一个节点指针都保存下来
删除节点的下标正好等于 int size = p.size()-n; //n为删除的倒数第n个节点
# include<iostream>
# include<vector>
# include<string>
# include<algorithm>
# include<math.h>
# include<climits>
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) {}
};
ListNode* removeNthFromEnd(ListNode* head, int n) {
vector<ListNode*>p;
ListNode* pp = head;
while (pp) {
p.push_back(pp);
pp = pp->next;
}
int size = p.size()-n;
if (p.size() == 0) {//不存在
return head;
}
else if (p.size() == 1) {//只有一个节点
delete(head);
return NULL;
}
else {//多个节点
if (!size) {//为首节点
head = p[size + 1];
delete(p[size]);
return head;
}
else if (size == p.size() - 1) {//尾巴节点
p[size - 1]->next = NULL;
delete(p[size]);
return head;
}
else {//非首尾节点
p[size - 1]->next = p[size]->next;
delete(p[size]);
return head;
}
}
}
int main(void) {
return 0;
}