Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
倒数第n个就是正数第length+1-n个,删掉就好~
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
if (!head)
return NULL;
int length = 1,count=1;
ListNode *addHead = new ListNode(-1);
addHead->next = head;
ListNode *target = head,*pretarget=addHead;
while (target->next)
{
++length;
target = target->next;
}
target = head;
while (count < (length + 1 - n))
{
pretarget = target;
target = target->next;
++count;
}
pretarget->next = target->next;
delete target;
return addHead->next;
}
};