Leetcode 19. Remove Nth Node From End of List 快慢指针,注意删头结点的特殊情况

  • 发现快指针跑n步后已经空了的话,说明这次要删倒数n,也就是整数第一个元素,那么要特殊对待
  • 记得删除元素用delete
/**
 * 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* fast = head;
        ListNode* slow = head;
        for(int i=0; i<n; i++)
            fast=fast->next;
        
        if(!fast){
            slow = slow ->next;
            ListNode* tmp = head;
            delete tmp;
            return slow;
        }
        while(fast&&fast->next){
            fast=fast->next;
            slow=slow->next;
        }
        ListNode* del = slow->next;
        slow->next=slow->next->next;
        delete del;
        return head;
    }
};

你可能感兴趣的:(算法)