Problem:
Given a linked list, remove the nth node from the end of list and return its head.
It’s great to use double pointer to delete node, the double pointer always store the next node’s address.
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode** t1 = &head, *t2 = head;//
cout<<(&t2)<<" "<<t2<<" "<<&head<<" "<<head<<endl;//t2'value is same as head's value,because
//thet all point to real head!.
cout<<t1<<endl;//t1's value is head pointer's address;
for(int i = 1; i < n; ++i)
{
t2 = t2->next;
cout<<" t2: "<<t2<<endl;
}
while(t2->next != NULL)
{
t1 = &((*t1)->next);//t1 store the next node's address
cout<<"t1:"<<t1<<endl;
cout<<"*t1:"<<*t1<<endl;
t2 = t2->next;
}
*t1 = (*t1)->next;//*t1 is next node ;
return head;
}
};
int main(int argc, char const *argv[])
{
Solution A;
int a[5]={1,2,3,4,5};
ListNode *head=new ListNode(a[0]);
ListNode *p=head;
int i=1;
while(i<5)
{
ListNode * q=new ListNode(a[i]);
p->next=q;
p=q;
i++;
}
p=head;
while(p!=NULL)
{
cout<<(*p).val<<endl;
p=p->next;
}
cout<<"-----"<<endl;
head=A.removeNthFromEnd(head,3);
while(head!=NULL)
{
cout<<head->val<<endl;
head=head->next;
}
return 0;
}
runtime snapshot better to understand