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.
建立一个新空节点,省去了处理头节点的困恼,用两个节点来遍历,p,q指向空节点,先把q节点移动n个位置,然后同时移动p,q ,当q指向最后一个节点时,p指向的下一个节点就是要删除的节点。
/**
* 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 *dumy=new ListNode(0);
ListNode *p=dumy;
ListNode *q=dumy;
dumy->next=head;
for(int i=0;i<n;i++)
q=q->next;
while(q->next!=NULL){
p=p->next ;
q=q->next ;
}
p->next =p->next ->next ; //删除P节点的下一个节点。
return dumy->next ; //返回头节点。
}
};