leetcode 19. 删除链表的倒数第 N 个结点
给你一个链表,删除链表的倒数第 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
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if(head==NULL&&n==0) return NULL;
if(head->next==NULL&&n==1) return NULL;
ListNode *p=head;
int len=0;
while(p!=NULL)
{
p=p->next;
len++;
}
int index=len-n+1;
ListNode *pre;
p=head;
if(index==1)
{
head=head->next;
delete p;
return head;
}
for(int i=1;i<index;i++){
pre=p;
p=p->next;
}
pre->next=p->next;
return head;
}
};
提交后通过: