http://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/
采用双指针的思路
1. 定义head1, head2 两个指针, head2先向前n步
2. head1, head2 同时向前,直到head2为NULL
3. head1 即为所要删除的节点
(为了便于处理,使用了一个头指针,具体算法略有不同但思路一致)
/**
* 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 * root = new ListNode(-1);
root->next = head;
ListNode * head1 = root;
ListNode * head2 = root;
int con = n+1;
while(con--) {
head2 = head2->next;
}
while(head2 && head1) {
head1 = head1->next;
head2 = head2->next;
}
head1->next = head1->next->next;
return root->next;
}
};