初级程序员必备的十大技能之基础数据结构与算法(三)

简介: 教程来源 https://rvtst.cn/ 栈是后进先出(LIFO)的受限线性表,仅允许在栈顶进行插入(push)和删除(pop)操作。本质如叠盘子:最后入者最先出。常见应用包括括号匹配、浏览器历史回退、逆波兰表达式求值等,高效且原理简洁。

四、栈:后进先出(LIFO)

栈是一种受限的线性表,只允许在一端(栈顶)进行插入和删除操作。

4.1 栈的本质
就像一叠盘子:你只能从顶部取盘子,也只能在顶部放盘子。最后放上去的盘子会被最先拿走。

// 栈的操作
// push(入栈):添加元素到栈顶
// pop(出栈):移除并返回栈顶元素
// peek(查看栈顶):返回栈顶元素但不移除
// isEmpty:检查栈是否为空

4.2 栈的实现

// 使用数组实现栈(最简单)
class Stack {
    constructor() {
        this.items = [];
    }

    // 入栈 - O(1)
    push(element) {
        this.items.push(element);
    }

    // 出栈 - O(1)
    pop() {
        if (this.isEmpty()) {
            return null;
        }
        return this.items.pop();
    }

    // 查看栈顶 - O(1)
    peek() {
        if (this.isEmpty()) {
            return null;
        }
        return this.items[this.items.length - 1];
    }

    // 检查是否为空
    isEmpty() {
        return this.items.length === 0;
    }

    // 获取大小
    size() {
        return this.items.length;
    }

    // 清空栈
    clear() {
        this.items = [];
    }

    // 打印
    print() {
        console.log(this.items.join(' ← '));
    }
}

// 使用示例
const stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.print();  // 1 ← 2 ← 3

console.log(stack.pop());  // 3
console.log(stack.peek()); // 2
console.log(stack.size()); // 2

4.3 栈的应用1:括号匹配
这是编译器检查语法错误的基础原理。

function isValidBrackets(str) {
    const stack = new Stack();
    const brackets = {
        '(': ')',
        '[': ']',
        '{': '}'
    };

    for (let i = 0; i < str.length; i++) {
        const char = str[i];

        // 如果是左括号,压入栈
        if (brackets[char]) {
            stack.push(char);
        }
        // 如果是右括号
        else if (char === ')' || char === ']' || char === '}') {
            // 栈为空,说明没有匹配的左括号
            if (stack.isEmpty()) {
                return false;
            }

            // 弹出栈顶的左括号
            const leftBracket = stack.pop();
            // 检查是否匹配
            if (brackets[leftBracket] !== char) {
                return false;
            }
        }
    }

    // 栈为空说明所有括号都匹配
    return stack.isEmpty();
}

// 测试
console.log(isValidBrackets("()"));        // true
console.log(isValidBrackets("()[]{}"));    // true
console.log(isValidBrackets("(]"));        // false
console.log(isValidBrackets("([)]"));      // false
console.log(isValidBrackets("{[]}"));      // true

// 执行过程解析:"{[]}"
// 读取 '{' → 压入栈: 栈 = ['{']
// 读取 '[' → 压入栈: 栈 = ['{', '[']
// 读取 ']' → 弹出 '[',匹配!栈 = ['{']
// 读取 '}' → 弹出 '{',匹配!栈 = []
// 结束,栈为空 → true

4.4 栈的应用2:浏览器历史记录(后退/前进)

class BrowserHistory {
    constructor() {
        this.backStack = new Stack();   // 后退栈
        this.forwardStack = new Stack(); // 前进栈
        this.current = null;
    }

    // 访问新页面
    visit(url) {
        if (this.current !== null) {
            // 将当前页面压入后退栈
            this.backStack.push(this.current);
            // 清空前栈(新访问会覆盖前进记录)
            this.forwardStack.clear();
        }
        this.current = url;
        console.log(`访问: ${url}`);
    }

    // 后退
    back() {
        if (this.backStack.isEmpty()) {
            console.log("无法后退");
            return null;
        }

        // 当前页面压入前进栈
        this.forwardStack.push(this.current);
        // 后退栈弹出页面作为当前页面
        this.current = this.backStack.pop();
        console.log(`后退到: ${this.current}`);
        return this.current;
    }

    // 前进
    forward() {
        if (this.forwardStack.isEmpty()) {
            console.log("无法前进");
            return null;
        }

        // 当前页面压入后退栈
        this.backStack.push(this.current);
        // 前进栈弹出页面作为当前页面
        this.current = this.forwardStack.pop();
        console.log(`前进到: ${this.current}`);
        return this.current;
    }

    // 查看当前页面
    getCurrent() {
        return this.current;
    }
}

// 使用示例
const browser = new BrowserHistory();
browser.visit("google.com");   // 访问: google.com
browser.visit("github.com");   // 访问: github.com
browser.visit("stackoverflow.com");  // 访问: stackoverflow.com

browser.back();     // 后退到: github.com
browser.back();     // 后退到: google.com
browser.forward();  // 前进到: github.com

4.5 栈的应用3:表达式求值(逆波兰表达式)

// 计算逆波兰表达式(后缀表达式)
// 例如:["2", "1", "+", "3", "*"] = (2+1)*3 = 9
function evalRPN(tokens) {
    const stack = new Stack();

    for (const token of tokens) {
        if (isOperator(token)) {
            // 弹出两个操作数
            const b = stack.pop();
            const a = stack.pop();
            const result = calculate(a, b, token);
            stack.push(result);
        } else {
            // 数字直接入栈
            stack.push(Number(token));
        }
    }

    return stack.pop();
}

function isOperator(token) {
    return token === '+' || token === '-' || token === '*' || token === '/';
}

function calculate(a, b, operator) {
    switch (operator) {
        case '+': return a + b;
        case '-': return a - b;
        case '*': return a * b;
        case '/': return Math.trunc(a / b);  // 整数除法
        default: return 0;
    }
}

// 执行过程:["2", "1", "+", "3", "*"]
// 读取 "2" → 栈 = [2]
// 读取 "1" → 栈 = [2, 1]
// 读取 "+" → 弹出1和2,计算2+1=3 → 栈 = [3]
// 读取 "3" → 栈 = [3, 3]
// 读取 "*" → 弹出3和3,计算3*3=9 → 栈 = [9]
// 结果 = 9

console.log(evalRPN(["2", "1", "+", "3", "*"]));  // 9

五、队列:先进先出(FIFO)

队列就像排队买东西:先来的人先服务,后来的人排在后面。
5.1 队列的本质
队列也是一种受限的线性表,插入在一端(队尾),删除在另一端(队首)。

// 队列的操作
// enqueue(入队):添加元素到队尾
// dequeue(出队):移除并返回队首元素
// front(查看队首):返回队首元素但不移除
// isEmpty:检查队列是否为空

5.2 队列的实现

// 使用数组实现队列
class Queue {
    constructor() {
        this.items = [];
    }

    // 入队 - O(1)(均摊)
    enqueue(element) {
        this.items.push(element);
    }

    // 出队 - O(n)(因为需要移动所有元素)
    // 这是数组实现的缺点
    dequeue() {
        if (this.isEmpty()) {
            return null;
        }
        return this.items.shift();  // shift 会移动所有元素
    }

    // 查看队首 - O(1)
    front() {
        if (this.isEmpty()) {
            return null;
        }
        return this.items[0];
    }

    isEmpty() {
        return this.items.length === 0;
    }

    size() {
        return this.items.length;
    }

    print() {
        console.log(this.items.join(' ← '));
    }
}

// 使用对象实现高效队列(所有操作 O(1))
class EfficientQueue {
    constructor() {
        this.items = {};
        this.frontIndex = 0;
        this.rearIndex = 0;
    }

    enqueue(element) {
        this.items[this.rearIndex] = element;
        this.rearIndex++;
    }

    dequeue() {
        if (this.isEmpty()) {
            return null;
        }
        const element = this.items[this.frontIndex];
        delete this.items[this.frontIndex];
        this.frontIndex++;
        return element;
    }

    front() {
        if (this.isEmpty()) {
            return null;
        }
        return this.items[this.frontIndex];
    }

    isEmpty() {
        return this.frontIndex === this.rearIndex;
    }

    size() {
        return this.rearIndex - this.frontIndex;
    }

    print() {
        const values = [];
        for (let i = this.frontIndex; i < this.rearIndex; i++) {
            values.push(this.items[i]);
        }
        console.log(values.join(' ← '));
    }
}

5.3 队列的应用:任务调度系统

class TaskScheduler {
    constructor() {
        this.queue = new Queue();
    }

    // 添加任务
    addTask(task, priority = false) {
        if (priority) {
            // 优先级高的任务插到队首
            // 简化实现,实际可以用优先队列
            const temp = new Queue();
            temp.enqueue(task);
            while (!this.queue.isEmpty()) {
                temp.enqueue(this.queue.dequeue());
            }
            this.queue = temp;
        } else {
            this.queue.enqueue(task);
        }
        console.log(`添加任务: ${task.name}`);
    }

    // 执行任务
    run() {
        while (!this.queue.isEmpty()) {
            const task = this.queue.dequeue();
            console.log(`执行: ${task.name}`);
            task.execute();
        }
    }
}

// 使用示例
const scheduler = new TaskScheduler();
scheduler.addTask({ name: "任务1", execute: () => console.log("  完成1") });
scheduler.addTask({ name: "任务2", execute: () => console.log("  完成2") });
scheduler.addTask({ name: "紧急任务", execute: () => console.log("  完成紧急") }, true);

scheduler.run();
// 输出:
// 添加任务: 任务1
// 添加任务: 任务2
// 添加任务: 紧急任务
// 执行: 紧急任务
//   完成紧急
// 执行: 任务1
//   完成1
// 执行: 任务2
//   完成2

5.4 队列的应用:广度优先搜索(BFS)
广度优先搜索是图和树的遍历算法,核心就是使用队列。

// 使用 BFS 查找图中的最短路径
class Graph {
    constructor() {
        this.adjacencyList = new Map();  // 邻接表
    }

    // 添加顶点
    addVertex(vertex) {
        if (!this.adjacencyList.has(vertex)) {
            this.adjacencyList.set(vertex, []);
        }
    }

    // 添加边(无向图)
    addEdge(v1, v2) {
        this.adjacencyList.get(v1).push(v2);
        this.adjacencyList.get(v2).push(v1);
    }

    // BFS 查找最短路径
    shortestPath(start, end) {
        const queue = new EfficientQueue();
        const visited = new Set();
        const parent = new Map();  // 记录路径

        queue.enqueue(start);
        visited.add(start);
        parent.set(start, null);

        while (!queue.isEmpty()) {
            const current = queue.dequeue();

            // 找到目标
            if (current === end) {
                // 重建路径
                const path = [];
                let node = end;
                while (node !== null) {
                    path.unshift(node);
                    node = parent.get(node);
                }
                return path;
            }

            // 遍历邻居
            const neighbors = this.adjacencyList.get(current);
            for (const neighbor of neighbors) {
                if (!visited.has(neighbor)) {
                    visited.add(neighbor);
                    parent.set(neighbor, current);
                    queue.enqueue(neighbor);
                }
            }
        }

        return null;  // 没有路径
    }
}

// 创建图
const graph = new Graph();
['A', 'B', 'C', 'D', 'E', 'F'].forEach(v => graph.addVertex(v));

graph.addEdge('A', 'B');
graph.addEdge('A', 'C');
graph.addEdge('B', 'D');
graph.addEdge('C', 'E');
graph.addEdge('D', 'E');
graph.addEdge('D', 'F');
graph.addEdge('E', 'F');

console.log(graph.shortestPath('A', 'F'));  // ['A', 'B', 'D', 'F'] 或 ['A', 'C', 'E', 'F'](取决于遍历顺序)

来源:
https://xcfsr.cn/

相关文章
|
13天前
|
人工智能 JSON 供应链
畅用7个月无影 JVS Claw |手把手教你把JVS改造成「科研与产业地理情报可视化大师」
LucianaiB分享零成本畅用JVS Claw教程(学生认证享7个月使用权),并开源GeoMind项目——将JVS改造为科研与产业地理情报可视化AI助手,支持飞书文档解析、地理编码与腾讯地图可视化,助力产业关系图谱构建。
23495 11
畅用7个月无影 JVS Claw |手把手教你把JVS改造成「科研与产业地理情报可视化大师」
|
17天前
|
人工智能 缓存 BI
Claude Code + DeepSeek V4-Pro 真实评测:除了贵,没别的毛病
JeecgBoot AI专题研究 把 Claude Code 接入 DeepSeek V4Pro,跑完 Skills —— OA 审批、大屏、报表、部署 5 大实战场景后的真实体验 ![](https://oscimg.oschina.net/oscnet/up608d34aeb6bafc47f
5475 20
Claude Code + DeepSeek V4-Pro 真实评测:除了贵,没别的毛病
|
18天前
|
人工智能 JSON BI
DeepSeek V4 来了!超越 Claude Sonnet 4.5,赶紧对接 Claude Code 体验一把
JeecgBoot AI专题研究 把 Claude Code 接入 DeepSeek V4Pro 的真实体验与避坑记录 本文记录我将 Claude Code 对接 DeepSeek 最新模型(V4Pro)后的真实体验,测试了 Skills 自动化查询和积木报表 AI 建表两个场景——有惊喜,也踩
6539 16
|
7天前
|
人工智能 缓存 Shell
Claude Code 全攻略:命令大全 + 实战工作流(完整版)
Claude Code 是一款运行在终端环境下的 AI 编码助手,能够直接在项目目录中理解代码结构、编辑文件、执行命令、执行开发计划,并支持持久化记忆、上下文压缩、后台任务、多模型切换等专业能力。对于日常开发、项目维护、快速重构、代码审查等场景,它可以大幅减少手动操作、提升编码效率。本文从常用命令、界面模式、核心指令、记忆机制、图片处理、进阶工作流等维度完整说明,帮助开发者快速上手并稳定使用。
1664 3
|
6天前
|
前端开发 API 内存技术
对比claude code等编程cli工具与deepseek v4的适配情况
DeepSeek V4发布后,多家编程工具因未适配其强制要求的`reasoning_content`字段而报错。本文对比Claude Code、GitHub Copilot、Langcli、OpenCode及DeepSeek-TUI等主流工具的兼容性:Claude Code需按官方方式配置;Langcli表现最佳,开箱即用且无报错;Copilot与OpenCode暂未修复问题;DeepSeek-TUI尚处早期阶段。
1130 3
对比claude code等编程cli工具与deepseek v4的适配情况
|
2天前
|
人工智能 BI 持续交付
Claude Code 深度适配 DeepSeek V4-Pro 实测:全场景通关与真实体验报告
在 AI 编程工具日趋主流的今天,Claude Code 凭借强大的任务执行、工具调用与工程化能力,成为开发者与自动化运维的核心效率工具。但随着原生模型账号稳定性问题频发,寻找一套兼容、稳定、能力在线的替代方案变得尤为重要。DeepSeek V4-Pro 作为新一代高性能大模型,提供了完整兼容 Claude 协议的 API 接口,只需简单配置即可无缝驱动 Claude Code,且在任务执行、工具调用、复杂流程处理上表现极为稳定。
838 0
|
1月前
|
人工智能 自然语言处理 安全
Claude Code 全攻略:命令大全 + 实战工作流(建议收藏)
本文介绍了Claude Code终端AI助手的使用指南,主要内容包括:1)常用命令如版本查看、项目启动和更新;2)三种工作模式切换及界面说明;3)核心功能指令速查表,包含初始化、压缩对话、清除历史等操作;4)详细解析了/init、/help、/clear、/compact、/memory等关键命令的使用场景和语法。文章通过丰富的界面截图和场景示例,帮助开发者快速掌握如何通过命令行和交互界面高效使用Claude Code进行项目开发,特别强调了CLAUDE.md文件作为项目知识库的核心作用。
27256 65
Claude Code 全攻略:命令大全 + 实战工作流(建议收藏)