算法1(蓝桥杯18)-删除链表的倒数第 N 个节点

问题:

给你一个链表,删除链表的倒数第 n 个节点,并且返回链表的头节点。

复制代码
输入:head = 1 -> 2 -> 3 -> 4 -> 5 -> null, n = 2
输出:1 -> 2 -> 3 -> 5 -> null

输入:head = 1 -> null, n = 1
输出:null

输入:head = 1 -> 2 -> null, n = 1
输出:1 -> null

解题思路:

使用快慢指针

(1)创建虚拟节点,简化边界条件的处理(这里虚拟节点的值不重要)

(2)创建快慢指针,指向虚拟节点

(3)使用循环让快指针先移动n步(假设删除倒数第2个节点)

(4)通过循环条件快指针的下一位不为空,使慢指针位于到被删除节点的前一个位置

(5)删除节点

完整代码:

javascript 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>删除链表的倒数第 N 个节点</title>
</head>
<body>
    <p>
    给你一个链表,删除链表的倒数第 n 个节点,并且返回链表的头节点。
    </p>
    <p>
        输入:head = 1 -> 2 -> 3 -> 4 -> 5 -> null, n = 2
        输出:1 -> 2 -> 3 -> 5 -> null
    </p>
</body>
<script>
    class LinkList {
        constructor(val,next){
            this.val=val
            this.next=next
        }

    }
    let head = new LinkList(1)
        head.next = new LinkList(2)
        head.next.next = new LinkList(3)
        head.next.next.next = new LinkList(4)
        head.next.next.next.next = new LinkList(5)
    removeNthFromEnd(head,2)
    function removeNthFromEnd(head, n) {
        let node = {
            val: 0,
            next: head
        }
        let f = s = node 
        while (n-- > 0) {
            f = f.next
        }
        while (f != null && f.next != null) {
            f = f.next
            s = s.next
        }
        s.next = s.next.next 
        console.log(node.next);
        
        return node.next
    }



</script>
</html>
相关推荐
m0_547486665 天前
《数据结构教程》全套 PPT课件2026
数据结构
tryxr5 天前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_35 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
All for pursuit.5 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.5 天前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
渡我白衣5 天前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe
晴天的雨.9926 天前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
无敌贵点大王6 天前
RTThread学习记录11——RT-Thread 设备模型吃透:UART/ADC/PWM/PIN 到底有什么区别?
c语言·stm32·学习·链表
淡海水6 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
Logic1016 天前
C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质