19. 删除链表的倒数第 N 个结点
19. 删除链表的倒数第 N 个结点
难度中等2492
给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
示例 1:

输入:head = [1,2,3,4,5], n = 2输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1输出:[]
示例 3:
输入:head = [1,2], n = 1输出:[1]
提示:
链表中结点的数目为
sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz
进阶:你能尝试使用一趟扫描实现吗?
第一种错法:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
struct ListNode *newhead = (struct ListNode*)malloc(sizeof(struct ListNode));
newhead->next = head;
struct ListNode *cur = newhead;
struct ListNode *last = cur;
while(1){
for(int i=0;i<n;i++){
last = last->next;
}
if(last->next==NULL){
struct ListNode* tmp = cur->next;
cur->next = last;
free(tmp);
return newhead->next;
}else{
cur=cur->next;
last = cur;
}
}
}
这里的last是只考虑了n是偶数的情况,当n为奇数时last将指向需要删除的元素,与循环中的代码矛盾。
第一种对法:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
struct ListNode *newhead = (struct ListNode*)malloc(sizeof(struct ListNode));
newhead->next = head;
struct ListNode *cur = newhead;
struct ListNode *last = cur;
while(1){
for(int i=0;i<=n;i++){
last = last->next;
}
if(last==NULL){
struct ListNode* tmp = cur->next;
cur->next = cur->next->next;
free(tmp);
return newhead->next;
}else{
cur=cur->next;
last = cur;
}
}
}