leetcode19Remove 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.
Try to do this in one pass.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode * function(ListNode * head, int * n)
{
ListNode * result;
if (head->next)
{
result = function(head->next, n);
}
else
{
result = NULL;
}
if (--*n == 0)
{
return result;
}
else
{
head->next = result;
return head;
}
}
ListNode* removeNthFromEnd(ListNode* head, int n) {
int m = n;
if (head == NULL)
{
return NULL;
}
ListNode * result = function(head, &m);
return result;
}
};
讨论区看到一个非常厉害的解决方法,用2个指针,先用一个指针走n-1个位置,然后第二个指针与第一个指针一起走,直到第一个指针为null,此时第二个指针就是要删除的节点,并且第二个指针使用的是二级指针的方式,可以直接通过二级指针的地址修改该节点上的值,非常巧妙。
class Solution
{
public:
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;
}
};