LeetCode 19. 删除链表的倒数第 N 个结点

力扣 LeetCode 19. 删除链表的倒数第 N 个结点

LeetCode 19. 删除链表的倒数第 N 个结点_第1张图片

LeetCode 19. 删除链表的倒数第 N 个结点_第2张图片

解题思路:利用双指针,一个快指针(fast),一个慢指针(slow) 

/**
 * 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* dummyHead = new ListNode();
        dummyHead->next = head;
        ListNode* fast = dummyHead;
        ListNode* slow = dummyHead;
        /*while(n-- && fast!=nullptr){
            fast = fast->next;
        }
        fast = fast->next;*/
        n++;
        while(n-- && fast!=nullptr){
            fast = fast->next;
        }
        while(fast){
            fast = fast->next;
            slow = slow->next;
        }
        ListNode *tmp = slow->next;  //C++释放内存的逻辑
        slow->next = tmp->next;
        delete tmp;
        return dummyHead->next;
    }
};

// 时间复杂度: O(n)
// 空间复杂度: O(1)

你可能感兴趣的:(leetcode,链表,算法,双指针,fast,slow)