Remove Nth Node From End of List
问题描述:
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.
Note:
Given n will always be valid.
知识补充:
指针:参考此文章c++指针详解
测试代码(c++):
ListNode* removeNthFromEnd(ListNode* head, int n)
{
ListNode** t1 = &head, *t2 = head;
for(int i = 1; i < n; ++i)
{
t2 = t2->next;
}
while(t2->next != NULL)
{
t1 = &((*t1)->next);
t2 = t2->next;
}
*t1 = (*t1)->next;
return head;
}
性能:
参考答案:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *t1 = head;
ListNode *t2 = head;
for(int i=0;i<n;i++)
{
t2 = t2->next;
}
if (!t2) return head->next;
while(t2->next!=NULL)
{
t1 = t1->next;
t2 = t2->next;
}
t1->next = t1->next->next;
return head;
}