力扣刷题笔记:删除链表的倒数第n个结点(暴力解法&双指针&递归)

Leetcode.19 删除链表的倒数第n个结点
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
力扣刷题笔记:删除链表的倒数第n个结点(暴力解法&双指针&递归)_第1张图片
1).暴力解法思路很简单,直接第一遍遍历整个链表,记录链表所有结点的个数,再用总个数减去倒数的个数,再次遍历删除标记的数;

/**
 * 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) {
        int count = 0;
        ListNode* cur = head;
        while(cur != NULL)
        {
            ++count;
            cur = cur->next;
        }
        int move = count - n;
        if (move < 0)
        {return head;}
        ListNode* node = new ListNode(0);
        node->next = head;
        ListNode* prev = node;
        for(int i = 0;i < move; i++)
        {
            prev = prev->next;
        }
        ListNode* del = prev->next;
        prev->next = del->next;
        delete del;
        return node->next;
    }
};

2).双指针法,类似于滑动窗口,设定快慢两个指针都指向哨兵结点,快指针先移动n+1位,慢指针保持不动,这样再使快慢两个指针同时移动,当快指针指向NULL时,慢指针正好指向需要删除结点的前一个结点。

/**
 * 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* node = new ListNode(0);
       node->next = head;
       ListNode* fast = node;
       ListNode* slow = node;
       while(n+1)
       {
           fast = fast->next;
           n--;
       }
       while(fast != NULL)
       {
           slow = slow->next;
           fast = fast->next;
       }
       ListNode* del = slow->next;
       slow->next = del->next;
       delete del;
       return node->next;
    }
};

3).递归法,设定一个计数值count,初始值为0,当不断移动指针递出去时count不变,当指针指向NULL后开始return后每移动一次count++,直到count==n时就不返回本身指针而是返回本身指针的next,做到删除的作用。这个做法非常巧妙,不过我写的乱七八糟太难看了,附上力扣评论区大佬写的,非常漂亮。

/**
 * 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:
    
       int cur=0;
    ListNode* removeNthFromEnd(ListNode* head, int n) {
       if(!head) return NULL;
       head->next = removeNthFromEnd(head->next,n);
       cur++;
       if(n==cur) return head->next;
       return head;
    }
};

你可能感兴趣的:(c++,leetcode)