1、Remove Nth Node From End of List
Given a linked list, remove the nth node from the end of list and return its head.
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.
删除从尾节点数的第n个节点~
用两个指针,同样的速度走,一个先走n步,然后一起走,当前面指针走到尾节点时,后面指针的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 dummy(-1);
dummy.next = head;
ListNode* p = &dummy;
ListNode* q = &dummy;
for(int i = 0; i < n; i++){
p = p->next;
}
while(p->next){
p = p->next;
q = q->next;
}
q->next = q->next->next;
return dummy.next;
}
};