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

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

思路🤔:

我们先创建一个哨兵位,这样便于我们头删,然后利用双指针 ,一个指针先走n+1步 (带哨兵位要多走一步),然后两个指针再一起走,当先走的指针结束,那么后走的指针下一个就是我们要删除的结点,最后用新的头结点接收即可。

代码🔎:

c 复制代码
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
        struct ListNode* guard = (struct ListNode*)malloc(sizeof(struct ListNode)); //创建哨兵位
        guard->next = head;
        struct ListNode* fast = guard;
        struct ListNode* slow = guard;

        while(n >= 0) //先走n+1步
        {
            fast = fast->next;
            n--;
        }

        while(fast != NULL) //fast走到空就结束,此时slow刚好在删除的前一个
        {
            slow = slow->next;
            fast = fast->next;
        }

        struct ListNode* del = slow->next;
        slow->next = slow->next->next;  //更新结点
        free(del);
        struct ListNode* newhead = guard->next; //创建新头
        free(guard);
        return newhead;
}
相关推荐
圣保罗的大教堂7 分钟前
leetcode 1161. 最大层内元素和 中等
leetcode
闲看云起10 分钟前
LeetCode-day6:接雨水
算法·leetcode·职场和发展
黛色正浓34 分钟前
leetCode-热题100-贪心合集(JavaScript)
javascript·算法·leetcode
一起努力啊~1 小时前
算法刷题--长度最小的子数组
开发语言·数据结构·算法·leetcode
leoufung2 小时前
LeetCode 221:Maximal Square 动态规划详解
算法·leetcode·动态规划
源代码•宸2 小时前
Leetcode—39. 组合总和【中等】
经验分享·算法·leetcode·golang·sort·slices
好易学·数据结构2 小时前
可视化图解算法77:零钱兑换(兑换零钱)
数据结构·算法·leetcode·动态规划·力扣·牛客网
AlenTech2 小时前
226. 翻转二叉树 - 力扣(LeetCode)
算法·leetcode·职场和发展
Tisfy2 小时前
LeetCode 1458.两个子序列的最大点积:动态规划
算法·leetcode·动态规划·题解·dp
求梦8202 小时前
【力扣hot100题】合并区间(9)
算法·leetcode·职场和发展