C*******n 发帖数: 193 | 1 class Solution {
public:
ListNode *removeNthFromEnd(ListNode *head, int n) {
if (n==0 || !head){
return NULL;
}
ListNode* res = new ListNode(0);
res->next = head;
head = res;
ListNode* p=head;
ListNode* q=head;
for (int i=0;i<=n;i++){
if (q){
q=q->next;
}else{
return NULL;
}
}
while (q){
p=p->next;
q=q->next;
}
p->next=p->next->next;
return head->next;
}
};
删除node从list, 这个有内存泄露么,怎么释放内存,对于那个被删除的节点? | J**9 发帖数: 835 | 2 What do you return?
The new list or the deleted node?
Assume you return the new list:
1) Free res before return
tmp = head->next;
head->next = NULL;
free(head);
return tmp;
2) tmp = p->next;
p->next=p->next->next;
free(tmp);
3)
The Nth one shall be the one after p, so
for (int i=0;i
4) return NULL; ==> return head->next? |
|