我做这种链表题通常都喜欢使用一个新的头结点,可以避免很多Base case。
而且这题如果不用新头结点的话,还得先遍历一次获得链表长度。
/**
* 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==NULL)
return head;
ListNode myhead(-1);
myhead.next = head;
ListNode *j = head;
while(n-->0)
j = j->next;
ListNode *i = &myhead;
while(j){
j = j->next;
i = i->next;
}
ListNode *tmp = i->next->next;
delete(i->next);
i->next = tmp;
return myhead.next;
}
};