给你一个链表,删除链表的倒数第 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
没啥好说的,学过考研408这个题目就是基本操作了,可能有几个边界情况但是问题不大:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode*slow=new ListNode();
ListNode*slow1=new ListNode();
ListNode*fast=new ListNode();
slow=head;
slow1=head;
fast=head;
if(head==nullptr||head->next==nullptr)
return nullptr;
for(int i=0;i<n-1;i++)
fast=fast->next;
if(fast->next==nullptr){
head=head->next;
return head;
}
while(fast->next!=nullptr)
{
if(slow!=head)
slow1=slow1->next;
fast=fast->next;
slow=slow->next;
}
slow1->next=slow->next;
return head;
}
};