Given a linked list, remove the n-th node from the end of list and return its head.
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.
Follow up:
Could you do this in one pass?
2级指针删除, 避免了prev变量, 也不需要判断是否为头指针的问题,也不用增加一个额外的head指针
先用l1 移动n步, 接着l1 和 l2 一起移动直到l1 到末尾
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode *l1=head, **l2=&head; for(int i=1;i<n;++i) //这里循环n-1次即可 l1=l1->next; while(l1->next) //注意l2的初始值是&head, 所以第一次循环后 l2的值为 &head->next, 接下来为 & head->next->next { l1=l1->next; l2=&(*l2)->next; } *l2=(*l2)->next; //此时l2指向需要删除的前一个节点的next, 所以直接赋值为下一个next即可 return head; } };