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.
设置p和q两个指针,p先向前移动n步。
然后p和q同时向前移动,知道p移动到链表尾部。
此时q的位置即为需要移除的节点。
/**
* 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) {
if(head==nullptr) return nullptr;
ListNode dummy(-1);
dummy.next = head;
ListNode *p = &dummy;
ListNode *q = &dummy;
for(int i=0;i<n;i++){
p = p->next;
}
while(p->next!=nullptr){
p = p->next;
q = q->next;
}
ListNode *temp = q->next;
q->next = q->next->next;
delete temp;
return dummy.next;
}
};