打卡 DAY 12 删除链表的倒数第N个节点

力扣原题链接

一、题目描述

 二、思路

  • 暴力解法:遍历一遍记录链表长度,然后再遍历一遍找到要删除的节点,删除;
  • 涉及到定位,可以使用双指针,因为题目说是删除倒数第N个,所以可以将指针设定为相隔(N )个节点,因此在当走在前头的指针(pre)走到NULL时,走在后头的指针刚好指向将要删除的节点的前一个节点。
  • e.g.删除倒数第一个节点👇

 三、解题过程

  • 定义虚拟头节点

  • 因为最后要输出头节点,且头节点有可能给删除掉,所以设置虚拟头节点,以便最后输出头节点:
    struct ListNode* pHead = (struct ListNode*)malloc(sizeof(struct ListNode));
    pHead -> next = head;
  • 定义pre和cur指针

  • cur指向虚拟头节点,pre指向与cur相隔N个节点的节点:
    struct ListNode* cur = pHead;
    struct ListNode* pre = pHead;
    for(; n >= 0; n --){
        pre = pre -> next;
    }
  • 移动pre和cur指针

  • 移动两个指针,直到pre指针指向NULL,此时cur指向将要删除的节点的前一个节点:
    while(pre) {
        pre = pre -> next;
        cur = cur -> next;
    }
  • 删除倒数第N个节点

  • 定义freeNode,即要删除的节点,同时令cur的next指针指向倒数第(N - 1)个节点,最后释放掉要删除的节点:

    struct ListNode* freeNode = cur -> next;
    cur -> next = freeNode -> next;
    free(freeNode);
  • 返回头节点

    return pHead -> next;

四、代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */

struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
    struct ListNode* pHead = (struct ListNode*)malloc(sizeof(struct ListNode));
    pHead -> next = head;
    struct ListNode* cur = pHead;
    struct ListNode* pre = pHead;
    for(; n >= 0; n --) {
        pre = pre -> next;
    }
    while(pre) {
        pre = pre -> next;
        cur = cur -> next;
    }
    struct ListNode* freeNode = cur -> next;
    cur -> next = freeNode -> next;
    free(freeNode);
    return pHead -> next;
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值