/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @param n: An integer.
* @return: The head of linked list.
*/
ListNode *removeNthFromEnd(ListNode *head, int n) {
// write your code here
if(head->next==NULL)//如果只有一个节点
return NULL;
ListNode* tmp=head;
int count=0;
while(tmp!=NULL){
count++;
tmp=tmp->next;
}
if(n==count)//如果要删除的是头结点
{
head=head->next;
return head;
}
tmp=head;
while(count>n+1){//否则找到节点,进行删除
tmp=tmp->next;
count--;
}
tmp->next=tmp->next->next;
return head;
}
};