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

题目:

在这里插入图片描述

代码:

// 方法1:两次遍历,先确定链表的长度。
// 之后再根据n序号,删除特定指针
// 此方法需要判断链表长度为1的情况 、 删除头指针、删除尾指针三种特殊情况

// 方法2:快慢指针
// 1 : 要设置虚拟节点dummpyHead 指向 head
// 2 : 设定双指针fast 和 slow,初始都指向虚拟头节点dummpy Head
// 3 : 移动fast指针,直到fast 与 slow之间间隔n个节点
// 4 : 同时移动fast 与 slow节点,直到fast为unullptr
// 5 : 将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) {
//         if(head == nullptr || head->next == nullptr) return nullptr;
//         int count = 0;
//         ListNode* index = head;
//         while(index != nullptr) {
//             count++;
//             index = index->next;
//         }
       
//         index = head;
//         // 针对两种特殊情况进行判断
//         if(count == n) {    // 删除头指针
//             index = index->next;
//             return index;   // 此处不返回,就无法覆盖head!!!
//         } else {
//             int count_de = count - n - 1;
//             while(count_de--) {
//                 index = index->next;
//             }
//             if(n == 1)  // 删除尾指针
//                 index->next = nullptr;
//             else
//                 index->next = index->next->next;
//         }
        
        
//         return head;
//     }
// };

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        // 构造虚拟头节点
        ListNode* dummpy_head = new ListNode(-1);
        dummpy_head->next = head;
        // 构造快慢指针分别指向虚拟头指针
        ListNode* fast = dummpy_head;
        ListNode* slow = dummpy_head;
        
        // 确保快慢指针之间间隔2个节点
       for(int i = 0; i < n+1; i++) {
            fast = fast->next;
        }
        
        // 移动slow指针到要删除的节点
        while(fast) {
            fast = fast->next;
            slow = slow->next;
        }

        // 删除指针
        slow->next = slow->next->next;

        return dummpy_head->next;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值