目录

  1. 题目描述
  2. 题目分析与思路
  3. 多语言代码实现
    • C++
    • Java
    • Python
    • C语言
    • JavaScript
  4. 复杂度分析
  5. B卷复用说明
  6. 总结

1️⃣ 题目描述

目录删除问题:
给定一个文件系统目录路径和相关文件或子目录信息,实现对指定目录及其所有子目录和文件的递归删除操作。

  • 输入通常包含目录树结构或路径集合。
  • 需要删除指定目录下所有内容,包括嵌套子目录。
  • 要求在删除过程中保证操作正确且高效。

2️⃣ 题目分析与思路

  • 核心思路:递归删除或使用栈/队列实现非递归遍历,先删除子节点再删除父目录。
  • 关键点
    • 文件和目录区分处理,目录先遍历子目录和文件。
    • 删除顺序:后进先出(后删除子目录和文件,最后删除目录本身)
    • 注意异常处理或边界情况(空目录、路径不存在等)。
  • 实现方式
    • 递归函数处理目录
    • 遍历目录下所有文件和子目录
    • 逐一删除文件和子目录
    • 最终删除该目录本身

3️⃣ 多语言代码实现

C++ 版本

#include <iostream>
#include <filesystem>

namespace fs = std::filesystem;

bool deleteDirectory(const fs::path& dirPath) {
    if (!fs::exists(dirPath)) {
        std::cerr << "路径不存在: " << dirPath << std::endl;
        return false;
    }
    if (!fs::is_directory(dirPath)) {
        std::cerr << "不是目录: " << dirPath << std::endl;
        return false;
    }

    std::error_code ec;
    fs::remove_all(dirPath, ec);
    if (ec) {
        std::cerr << "删除失败: " << ec.message() << std::endl;
        return false;
    }
    return true;
}

int main() {
    std::string path;
    std::cout << "请输入要删除的目录路径:";
    std::getline(std::cin, path);

    if (deleteDirectory(path)) {
        std::cout << "目录删除成功!" << std::endl;
    } else {
        std::cout << "目录删除失败!" << std::endl;
    }

    return 0;
}

Java 版本

import java.io.File;

public class DeleteDirectory {
    public static boolean deleteDir(File dir) {
        if (!dir.exists()) {
            System.err.println("路径不存在: " + dir.getAbsolutePath());
            return false;
        }
        if (!dir.isDirectory()) {
            System.err.println("不是目录: " + dir.getAbsolutePath());
            return false;
        }
        File[] files = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    if (!deleteDir(file)) return false;
                } else {
                    if (!file.delete()) {
                        System.err.println("删除文件失败: " + file.getAbsolutePath());
                        return false;
                    }
                }
            }
        }
        return dir.delete();
    }

    public static void main(String[] args) {
        String path = System.console().readLine("请输入要删除的目录路径:");
        File dir = new File(path);
        if (deleteDir(dir)) {
            System.out.println("目录删除成功!");
        } else {
            System.out.println("目录删除失败!");
        }
    }
}

Python 版本

import shutil
import os

def delete_directory(path):
    if not os.path.exists(path):
        print(f"路径不存在: {path}")
        return False
    if not os.path.isdir(path):
        print(f"不是目录: {path}")
        return False
    try:
        shutil.rmtree(path)
        return True
    except Exception as e:
        print(f"删除失败: {e}")
        return False

if __name__ == "__main__":
    path = input("请输入要删除的目录路径:")
    if delete_directory(path):
        print("目录删除成功!")
    else:
        print("目录删除失败!")

C 语言版本(Linux系统,使用 POSIX API)

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <errno.h>

int delete_directory(const char *path) {
    DIR *dir = opendir(path);
    if (!dir) {
        perror("打开目录失败");
        return -1;
    }
    struct dirent *entry;
    char fullpath[4096];
    struct stat statbuf;

    while ((entry = readdir(dir)) != NULL) {
        if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, ".."))
            continue;

        snprintf(fullpath, sizeof(fullpath), "%s/%s", path, entry->d_name);
        if (stat(fullpath, &statbuf) == -1) {
            perror("stat失败");
            closedir(dir);
            return -1;
        }
        if (S_ISDIR(statbuf.st_mode)) {
            if (delete_directory(fullpath) == -1) {
                closedir(dir);
                return -1;
            }
        } else {
            if (unlink(fullpath) == -1) {
                perror("删除文件失败");
                closedir(dir);
                return -1;
            }
        }
    }
    closedir(dir);
    if (rmdir(path) == -1) {
        perror("删除目录失败");
        return -1;
    }
    return 0;
}

int main() {
    char path[4096];
    printf("请输入要删除的目录路径:");
    if (fgets(path, sizeof(path), stdin) == NULL) {
        fprintf(stderr, "输入错误\n");
        return 1;
    }
    path[strcspn(path, "\n")] = 0;  // 去除换行符

    if (delete_directory(path) == 0) {
        printf("目录删除成功!\n");
    } else {
        printf("目录删除失败!\n");
    }
    return 0;
}

JavaScript (Node.js) 版本

const fs = require('fs');
const path = require('path');

function deleteDirectory(dirPath) {
    if (!fs.existsSync(dirPath)) {
        console.error(`路径不存在: ${dirPath}`);
        return false;
    }
    const stats = fs.statSync(dirPath);
    if (!stats.isDirectory()) {
        console.error(`不是目录: ${dirPath}`);
        return false;
    }
    fs.readdirSync(dirPath).forEach(file => {
        const curPath = path.join(dirPath, file);
        if (fs.lstatSync(curPath).isDirectory()) {
            deleteDirectory(curPath);
        } else {
            fs.unlinkSync(curPath);
        }
    });
    fs.rmdirSync(dirPath);
    return true;
}

// 运行示例
const readline = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
});

readline.question('请输入要删除的目录路径:', path => {
    if (deleteDirectory(path)) {
        console.log('目录删除成功!');
    } else {
        console.log('目录删除失败!');
    }
    readline.close();
});

4️⃣ 复杂度分析

  • 时间复杂度:O(N),N为目录及其所有子文件和目录的总数量。
  • 空间复杂度:递归调用栈深度取决于目录层级深度,最坏为O(D),D为目录最大层级数。

5️⃣ B卷复用说明

  • 2025 B卷与其他版本存在部分题目复用,目录删除问题在B卷中同样适用。
  • 代码结构与思路在不同语言版本间保持一致,便于快速迁移和复用。
  • 注意不同环境API差异,合理调整。

6️⃣ 总结

  • 目录删除是文件系统操作中的经典题目,考察递归与文件IO能力。
  • 各语言实现差异主要在于系统API调用和异常处理方式。
  • 理解底层递归删除逻辑,掌握多语言实现,有助于应对类似机试题目。
  • 预留异常处理和边界检查是提升代码健壮性的关键。

如果你需要,我还可以帮你准备本题的详细测试用例设计,或者结合华为OD机试其他相关题目帮你制作复习资料,随时告诉我!