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;
}
相关推荐
圣保罗的大教堂6 小时前
leetcode 2540. 最小公共值 简单
leetcode
wljy16 小时前
二、进制状态转换
linux·运维·服务器·c语言·c++
01_ice7 小时前
C语言数据在内存中的存储
c语言·开发语言
bucenggaibian7 小时前
《C语言》编程前置:计算机底层逻辑(诞生的基础)
c语言·程序框架·编译运行·内存地址·底层逻辑
小娄~~9 小时前
C语言卷子错题集
c语言·开发语言·数据结构
洛水水10 小时前
【力扣100题】53.最长回文子串
算法·leetcode·职场和发展
过期动态11 小时前
【LeetCode 热题 100】盛最多水的容器
java·数据结构·spring boot·算法·leetcode·spring cloud·职场和发展
凌波粒11 小时前
LeetCode--700.二叉搜索树中的搜索(二叉树)
算法·leetcode·职场和发展
洛水水12 小时前
【力扣100题】58.轮转数组
算法·leetcode
风筝在晴天搁浅12 小时前
阿里 LeetCode 876.链表的中间节点
算法·leetcode·链表