solution.cpp 530 字节
Newer Older
每日一练社区's avatar
每日一练社区 已提交
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
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) {}
};
#include <vector>
class Solution
{
public:
	ListNode *removeNthFromEnd(ListNode *head, int n)
	{
		ListNode empty_node(0, head);
		ListNode *p = &empty_node;
		std::vector<ListNode *> pv;
		while (p != nullptr)
		{
			pv.push_back(p);
			p = p->next;
		}
		p = pv[pv.size() - 1 - n];
		p->next = p->next->next;
		return empty_node.next;
	}
};