uacs2024

导航

leetcode19-删除链表的倒数第N个结点

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

 

方法一:快慢指针法

/**
 * 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->next) return nullptr;
        ListNode *dummyHead = new ListNode;
        dummyHead->next=head;
        ListNode *fast=dummyHead;
        for(int i=0;i<n;i++)
        {
            fast=fast->next;
        }
        if(!fast->next) return head->next;  
    //如果已经遍历到最后一个结点,则说明删除的是第一个结点,直接返回head->next ListNode
*slow=dummyHead; while(fast->next) { slow=slow->next; fast=fast->next; } slow->next=slow->next->next; return head; } };

方法二:遍历两次链表,第一次计算得出总长度,第二次通过计数遍历到需要删除的元素的前驱结点

/**
 * 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->next) return nullptr;
        ListNode *dummyHead = new ListNode;
        dummyHead->next=head;
        ListNode *p=dummyHead;
        int count=0;
        while(p->next)
        {
            count++;
            p=p->next;
        }
        p = dummyHead;
        int count2 = count-n;
        if(count2==0)   return head->next;
        int count1=0;
        while(count1<count2)
        {
            p=p->next;count1++;
        }
        p->next=p->next->next;
        return head;
    }
};

方法三:栈

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* dummy = new ListNode(0, head);
        stack<ListNode*> stk;
        ListNode* cur = dummy;
        while (cur) 
        {
            stk.push(cur);
            cur = cur->next;
        }
        for (int i = 0; i < n; ++i) 
        {
            stk.pop();
        }
        ListNode* prev = stk.top();
        prev->next = prev->next->next;
        ListNode* ans = dummy->next;
        delete dummy;
        return ans;
    }
};

方法四:递归  看不懂(ó﹏ò。)

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;
    }
};

 

posted on 2022-09-14 16:12  ᶜʸᵃⁿ  阅读(13)  评论(0编辑  收藏  举报