虽然是O(n),但是"O(2n)"应该尝试优化成O(n),这样在多\长链表用例才能占绝对优势.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
if (head==NULL){
return head;
}
if(head->next==NULL&&n==1){
return NULL;
}
struct ListNode* pointer=head;
int size=1;
while(pointer->next!=NULL){
pointer=pointer->next;
size++;
}
int idx=size-n;
if(idx==0){
head=head->next;
return head;
}
pointer=head;
while(idx-->1){
pointer=pointer->next;
}
pointer->next=pointer->next->next;
return head;
}
使用快慢指针
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
struct ListNode* fast=head;
struct ListNode* slow=head;
while(n--){//快指针先走n步
if (fast->next==NULL){
return head->next;
}
fast=fast->next;
}
while(fast->next!=NULL){
fast=fast->next;
slow=slow->next;
}
slow->next=slow->next->next;
return head;
}
理论更快的写法居然多次运行稳定在下图的时间… 估计是用例原因