LeetCode 19. Remove Nth Node From End of List
原题链接
简单
作者:
空く7です
,
2022-05-01 12:04:36
,
所有人可见
,
阅读 201
/**
* 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) {
if(head==nullptr||head->next==nullptr){
return nullptr;
}
ListNode* fast=head;
ListNode* slow =head;
for(int i=0;i<n;i++){
fast=fast->next;
}
if(fast==nullptr){
return head->next;
}
while(fast->next!=nullptr){
fast = fast->next;
slow = slow->next;
}
slow->next=slow->next->next;
return head;
}
};