您的位置:首页 > Web前端 > Node.js

(Leetcode)Double pointer to implement delete Linklist node

2015-09-11 04:21 507 查看
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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: