题目描述:
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.
一次遍历即可删除倒数第n个节点,可以采用两个指针的方法,第一个指针p1比第二个指针p2早n步出发,当p1到达链表最后一个元素时,即p1->next=NULL,第二个指针到达倒数第n+1个节点,此时只要将p2->next=p2->next->next即可除去倒数第n个节点。但是需要注意的是,n可以为链表节点的总数,此时p1会指向NULL,如果还要判断if(p1->next==NULL)就会出错,所以应该先行判断,当p1=NULL时,说明除去第一个节点,返回head->next。
/**
* 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* p1=head;
ListNode* p2=head;
for(int i=0;i<n;i++)
p1=p1->next;
if(p1==NULL) return head->next;
while(p1->next!=NULL)
{
p1=p1->next;
p2=p2->next;
}
p2->next=p2->next->next;
return head;
}
};