Given a linked list, remove the n-th node from the end of list and return its head.
问题描述:删除链表倒数第n个节点。
设置新的head,统计链表长度,当删除第一个节点时需要额外处理,否则当链表长度为1时返回的head并未经过处理。
class Solution {
public:
ListNode * removeNthFromEnd(ListNode* head, int n) {
ListNode* p1 = head;
ListNode* p2 = new ListNode(0);
p2->next = head;
int l = 0, k = 0;
while (p1 != NULL) //统计链表长度
{
p1 = p1->next;
l++;
}
if (n == l) //为了删除第一个节点
{
return head->next;
}
while (p2 &&p2->next)
{
if (k == l - n)
{
p2->next = p2->next->next;
}
p2 = p2->next;
k++;
}
return head;
}
};