LC 19. 删除链表的倒数第 N 个结点
https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
//定义一个p指针,用来遍历整个链表,获取长度
ListNode *p=head;
//定义初始结点个数为1
int sum=1;
while(p->next!=nullptr){
p=p->next;
sum++;
}
//获取正向索引
int index=sum-n;
//如果只有一个结点,直接返回空
if(sum==1) return nullptr;
//定义两个游标
ListNode *pre=head;
ListNode *cur=pre->next;
//判断是否删除头结点
if(index==0){
head=cur;
delete pre;
return head;
}
//遍历查找要删除的结点,cur所指
while(index>1){
pre=pre->next;
cur=cur->next;
index--;
}
//更改pre的指向
pre->next=cur->next;
//delete cur
delete cur;
return head;
}
};
- 复制链接
- 举报