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.
题意:如题。
解法:p,q两个指针q先走n步,然后p,q一起走,q到头时p指向的就是倒数第n个。
/**
* 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 newList(0);
newList.next = head;
ListNode *p = &newList, *q = &newList;
for(int i = 0; i < n; i++){
q = q->next;
}
while(q->next){
p = p->next;
q = q->next;
}
ListNode *tmp = p->next;
p->next = p->next->next;
delete tmp;
return newList.next;
}
};