【懒人精灵】小飞侠插件专题——栈和队列相关的操作

内容说明

QueueOps 和 StackOps 提供了完整的队列和栈数据结构功能,包括:

  • 队列操作:创建队列、入队、出队、查看队首/队尾、大小查询、清空等
  • 栈操作:创建栈、入栈、出栈、查看栈顶、大小查询、清空等
  • 多实例管理:支持通过唯一 ID 管理多个队列/栈实例
  • 数据转换:支持将队列/栈转换为 JSON 数组格式

功能列表

队列功能(QueueOps)

  • create(id: String?): 创建队列实例
  • enqueue(id: String?, element: String?): 将元素添加到队列尾部(入队)
  • dequeue(id: String?): 从队列头部移除并返回元素(出队)
  • peek(id: String?): 查看队列头部元素,但不移除(查看队首)
  • peekLast(id: String?): 查看队列尾部元素,但不移除(查看队尾)
  • size(id: String?): 获取队列的大小
  • isEmpty(id: String?): 检查队列是否为空
  • clear(id: String?): 清空队列中的所有元素
  • remove(id: String?): 删除队列实例
  • toJsonArray(id: String?): 将队列转换为 JSON 数组字符串

栈功能(StackOps)

  • create(id: String?): 创建栈实例
  • push(id: String?, element: String?): 将元素添加到栈顶(入栈)
  • pop(id: String?): 从栈顶移除并返回元素(出栈)
  • peek(id: String?): 查看栈顶元素,但不移除(查看栈顶)
  • size(id: String?): 获取栈的大小
  • isEmpty(id: String?): 检查栈是否为空
  • clear(id: String?): 清空栈中的所有元素
  • remove(id: String?): 删除栈实例
  • toJsonArray(id: String?): 将栈转换为 JSON 数组字符串

OOP 调用例子

-- ============================================
-- 队列和栈示例
-- 演示如何使用 XfxPlugin.lua 调用 QueueOps 和 StackOps
-- ============================================

print('========== 队列和栈示例 ==========')

-- 加载 XfxPlugin.lua 类
local xfxModule = require('lib/XfxPlugin')

-- 创建 XFX 对象实例
local xfx = xfxModule:new({
    apkName = 'xfxPlugin-release.apk',  -- APK 文件名
})

-- 获取 QueueOps 和 StackOps 对象
local QueueOps = xfx:getOps('queueOps')
local StackOps = xfx:getOps('stackOps')

if not QueueOps or not StackOps then
    error('无法获取 QueueOps 或 StackOps 对象')
end

print('开始队列和栈示例...')

-- ============================================
-- 1. 队列基本操作
-- ============================================
print('\n--- 1. 队列基本操作 ---')

-- 创建队列
local queueId = 'myQueue'
if QueueOps.create(queueId) then
    print('队列创建成功:' .. queueId)
else
    error('队列创建失败')
end

-- 入队操作
print('入队元素:')
QueueOps.enqueue(queueId, '元素1')
QueueOps.enqueue(queueId, '元素2')
QueueOps.enqueue(queueId, '元素3')
print('已入队 3 个元素')

local items = {'苹果', '香蕉', '橙子', '葡萄'}
for i = 1, #items do
    if QueueOps.enqueue(queueId, items[i]) then
        print('  入队:' .. items[i])
    end
end

-- 查看队列大小
local queueSize = QueueOps.size(queueId)
print('队列大小:' .. tostring(queueSize))

-- 查看队首元素
local head = QueueOps.peek(queueId)
print('队首元素:' .. tostring(head))

-- 查看队尾元素
local tail = QueueOps.peekLast(queueId)
print('队尾元素:' .. tostring(tail))

-- 出队操作
print('\n出队操作:')
while not QueueOps.isEmpty(queueId) do
    local element = QueueOps.dequeue(queueId)
    print('出队:' .. tostring(element))
end

-- 检查队列是否为空
local isEmpty = QueueOps.isEmpty(queueId)
print('队列是否为空:' .. tostring(isEmpty))

-- ============================================
-- 2. 栈基本操作
-- ============================================
print('\n--- 2. 栈基本操作 ---')

-- 创建栈
local stackId = 'myStack'
if StackOps.create(stackId) then
    print('栈创建成功:' .. stackId)
else
    error('栈创建失败')
end

-- 入栈操作
print('入栈元素:')
StackOps.push(stackId, '元素A')
StackOps.push(stackId, '元素B')
StackOps.push(stackId, '元素C')
print('已入栈 3 个元素')

local stackItems = {'第一层', '第二层', '第三层', '第四层'}
for i = 1, #stackItems do
    if StackOps.push(stackId, stackItems[i]) then
        print('  入栈:' .. stackItems[i])
    end
end

-- 查看栈大小
local stackSize = StackOps.size(stackId)
print('栈大小:' .. tostring(stackSize))

-- 查看栈顶元素
local top = StackOps.peek(stackId)
print('栈顶元素:' .. tostring(top))

-- 出栈操作
print('\n出栈操作(后进先出):')
while not StackOps.isEmpty(stackId) do
    local element = StackOps.pop(stackId)
    print('出栈:' .. tostring(element))
end

-- 检查栈是否为空
isEmpty = StackOps.isEmpty(stackId)
print('栈是否为空:' .. tostring(isEmpty))

-- ============================================
-- 3. 多实例管理
-- ============================================
print('\n--- 3. 多实例管理 ---')

-- 创建多个队列实例
QueueOps.create('queue1')
QueueOps.create('queue2')
QueueOps.create('queue3')

-- 向不同队列添加元素
QueueOps.enqueue('queue1', '队列1的元素1')
QueueOps.enqueue('queue1', '队列1的元素2')
QueueOps.enqueue('queue2', '队列2的元素1')
QueueOps.enqueue('queue3', '队列3的元素1')

-- 查看各个队列的大小
print('queue1 大小:' .. tostring(QueueOps.size('queue1')))
print('queue2 大小:' .. tostring(QueueOps.size('queue2')))
print('queue3 大小:' .. tostring(QueueOps.size('queue3')))

-- 创建多个栈实例
StackOps.create('stack1')
StackOps.create('stack2')

-- 向不同栈添加元素
StackOps.push('stack1', '栈1的元素1')
StackOps.push('stack1', '栈1的元素2')
StackOps.push('stack2', '栈2的元素1')

print('stack1 大小:' .. tostring(StackOps.size('stack1')))
print('stack2 大小:' .. tostring(StackOps.size('stack2')))

-- ============================================
-- 4. 转换为 JSON 数组
-- ============================================
print('\n--- 4. 转换为 JSON 数组 ---')

-- 向队列添加元素
local jsonQueueId = 'jsonQueue'
QueueOps.create(jsonQueueId)
QueueOps.enqueue(jsonQueueId, '苹果')
QueueOps.enqueue(jsonQueueId, '香蕉')
QueueOps.enqueue(jsonQueueId, '橙子')

-- 转换为 JSON 数组
local queueJson = QueueOps.toJsonArray(jsonQueueId)
print('队列 JSON:' .. queueJson)

-- 向栈添加元素
local jsonStackId = 'jsonStack'
StackOps.create(jsonStackId)
StackOps.push(jsonStackId, '第一')
StackOps.push(jsonStackId, '第二')
StackOps.push(jsonStackId, '第三')

-- 转换为 JSON 数组
local stackJson = StackOps.toJsonArray(jsonStackId)
print('栈 JSON:' .. stackJson)

-- ============================================
-- 5. 清空和删除操作
-- ============================================
print('\n--- 5. 清空和删除操作 ---')

-- 创建并填充队列
local clearQueueId = 'clearQueue'
QueueOps.create(clearQueueId)
QueueOps.enqueue(clearQueueId, '元素1')
QueueOps.enqueue(clearQueueId, '元素2')
QueueOps.enqueue(clearQueueId, '元素3')

print('清空前队列大小:' .. tostring(QueueOps.size(clearQueueId)))

-- 清空队列
if QueueOps.clear(clearQueueId) then
    print('队列清空成功')
    print('清空后队列大小:' .. tostring(QueueOps.size(clearQueueId)))
end

-- 删除队列实例
if QueueOps.remove(clearQueueId) then
    print('队列删除成功')
    print('删除后队列大小:' .. tostring(QueueOps.size(clearQueueId)))  -- 应该返回 -1
end

-- 栈的清空和删除
local clearStackId = 'clearStack'
StackOps.create(clearStackId)
StackOps.push(clearStackId, '元素1')
StackOps.push(clearStackId, '元素2')

print('清空前栈大小:' .. tostring(StackOps.size(clearStackId)))

if StackOps.clear(clearStackId) then
    print('栈清空成功')
    print('清空后栈大小:' .. tostring(StackOps.size(clearStackId)))
end

if StackOps.remove(clearStackId) then
    print('栈删除成功')
    print('删除后栈大小:' .. tostring(StackOps.size(clearStackId)))  -- 应该返回 -1
end

print('\n========== 队列和栈示例完成 ==========')

直接调用例子


import('com.nx.assist.lua.LuaEngine')

-- ============================================
-- 方式二:直接调用方式(不推荐,但可以了解底层实现)
-- ============================================
print('========== 方式二:直接调用方式 ==========')

local loader = LuaEngine.loadApk('xfxPlugin-release.apk')
if not loader then
    error('Failed to load APK')
end

local UtilCodeMain = loader.loadClass('com.xfx.plugin.Main')
if not UtilCodeMain then
    error('Failed to load Class')
end

-- 初始化插件(需要 Context)
local context = LuaEngine.getContext()
UtilCodeMain.init(context)

-- 获取 QueueOps 和 StackOps 对象
local QueueOps = UtilCodeMain.queueOps()
local StackOps = UtilCodeMain.stackOps()

if not QueueOps or not StackOps then
    error('无法获取 QueueOps 或 StackOps 对象')
end

print('开始队列和栈示例...')

-- 创建队列
QueueOps.create('myQueue')

-- 入队
QueueOps.enqueue('myQueue', '元素1')
QueueOps.enqueue('myQueue', '元素2')

-- 出队
local element = QueueOps.dequeue('myQueue')
print('出队元素:' .. tostring(element))

-- 创建栈
StackOps.create('myStack')

-- 入栈
StackOps.push('myStack', '元素A')
StackOps.push('myStack', '元素B')

-- 出栈
local stackElement = StackOps.pop('myStack')
print('出栈元素:' .. tostring(stackElement))

实际应用示例

示例 1:任务队列管理

local xfxModule = require('lib/XfxPlugin')
local xfx = xfxModule:new({apkName = 'xfxPlugin-release.apk'})

local QueueOps = xfx:getOps('queueOps')

if not QueueOps then
    error('无法获取 QueueOps 对象')
end

-- 创建任务队列
local taskQueueId = 'taskQueue'
QueueOps.create(taskQueueId)

-- 添加任务
local tasks = {'下载文件', '处理图片', '上传数据', '发送邮件', '清理缓存'}
for i = 1, #tasks do
    QueueOps.enqueue(taskQueueId, tasks[i])
end

print('任务队列已创建,共 ' .. tostring(QueueOps.size(taskQueueId)) .. ' 个任务')

-- 处理任务(FIFO:先进先出)
print('\n开始处理任务:')
local taskCount = 0
while not QueueOps.isEmpty(taskQueueId) do
    local task = QueueOps.dequeue(taskQueueId)
    taskCount = taskCount + 1
    print(string.format('任务 %d:%s', taskCount, task))
    -- 模拟任务处理
    sleep(500)
end

print('所有任务处理完成')

示例 2:表达式求值(使用栈)

local xfxModule = require('lib/XfxPlugin')
local xfx = xfxModule:new({apkName = 'xfxPlugin-release.apk'})

local StackOps = xfx:getOps('stackOps')

if not StackOps then
    error('无法获取 StackOps 对象')
end

-- 使用栈来反转字符串
local stackId = 'reverseStack'
StackOps.create(stackId)

local text = 'Hello World'
print('原字符串:' .. text)

-- 将每个字符入栈
for i = 1, #text do
    local char = string.sub(text, i, i)
    StackOps.push(stackId, char)
end

-- 出栈并拼接(实现反转)
local reversed = ''
while not StackOps.isEmpty(stackId) do
    reversed = reversed .. StackOps.pop(stackId)
end

print('反转后:' .. reversed)
local xfxModule = require('lib/XfxPlugin')
local xfx = xfxModule:new({apkName = 'xfxPlugin-release.apk'})

local StackOps = xfx:getOps('stackOps')

if not StackOps then
    print('无法获取 StackOps 对象')
    return
end

-- 创建操作数栈
local operandStackId = 'operandStack'
StackOps.create(operandStackId)

-- 模拟表达式求值:将操作数压入栈
local operands = {'3', '4', '5', '6'}
print('表达式:3 + 4 * 5 - 6')
print('\n将操作数压入栈:')
for i = 1, #operands do
    StackOps.push(operandStackId, operands[i])
    print('  压入:' .. operands[i])
end

-- 弹出操作数进行计算(逆序)
print('\n弹出操作数进行计算:')
local result = 0
local count = 1
while not StackOps.isEmpty(operandStackId) do
    local operand = StackOps.pop(operandStackId)
    if operand then
        local num = tonumber(operand) or 0
        print('  弹出:' .. operand)
        -- 这里只是演示,实际表达式求值需要更复杂的逻辑
    end
end

示例 3:消息队列(生产者-消费者模式)

local xfxModule = require('lib/XfxPlugin')
local xfx = xfxModule:new({apkName = 'xfxPlugin-release.apk'})

local QueueOps = xfx:getOps('queueOps')

if not QueueOps then
    error('无法获取 QueueOps 对象')
end

local messageQueueId = 'messageQueue'
QueueOps.create(messageQueueId)

-- 模拟生产者:添加消息
local function producer()
    local messages = {'消息1', '消息2', '消息3', '消息4', '消息5'}
    for i = 1, #messages do
        QueueOps.enqueue(messageQueueId, messages[i])
        print('生产者:发送 ' .. messages[i])
        sleep(300)
    end
end

-- 模拟消费者:处理消息
local function consumer()
    while true do
        if not QueueOps.isEmpty(messageQueueId) then
            local message = QueueOps.dequeue(messageQueueId)
            print('消费者:处理 ' .. tostring(message))
        else
            print('消费者:队列为空,等待...')
            sleep(500)
        end
        sleep(200)
    end
end

-- 启动生产者
producer()

-- 处理消息
print('\n开始消费消息:')
while not QueueOps.isEmpty(messageQueueId) do
    local message = QueueOps.dequeue(messageQueueId)
    print('处理消息:' .. tostring(message))
    sleep(200)
end
local xfxModule = require('lib/XfxPlugin')
local xfx = xfxModule:new({apkName = 'xfxPlugin-release.apk'})

local QueueOps = xfx:getOps('queueOps')

if not QueueOps then
    print('无法获取 QueueOps 对象')
    return
end

-- 创建消息队列
local messageQueueId = 'messageQueue'
QueueOps.create(messageQueueId)

-- 模拟接收消息
local function receiveMessage(msg)
    QueueOps.enqueue(messageQueueId, msg)
    print('收到消息:' .. msg)
end

-- 模拟发送消息
local function sendMessage()
    if not QueueOps.isEmpty(messageQueueId) then
        local msg = QueueOps.dequeue(messageQueueId)
        print('发送消息:' .. msg)
        return true
    end
    return false
end

-- 接收多条消息
receiveMessage('消息1')
receiveMessage('消息2')
receiveMessage('消息3')

-- 处理消息队列
print('\n处理消息队列:')
while sendMessage() do
    sleep(200)
end

print('消息队列处理完成')

示例 4:撤销操作(使用栈)

local xfxModule = require('lib/XfxPlugin')
local xfx = xfxModule:new({apkName = 'xfxPlugin-release.apk'})

local StackOps = xfx:getOps('stackOps')

if not StackOps then
    error('无法获取 StackOps 对象')
end

-- 使用栈实现撤销功能
local undoStackId = 'undoStack'
StackOps.create(undoStackId)

-- 模拟用户操作
local operations = {'输入文字', '删除文字', '复制文字', '粘贴文字', '格式化文字'}
print('执行操作:')
for i = 1, #operations do
    local op = operations[i]
    print('  ' .. tostring(i) .. '. ' .. op)
    StackOps.push(undoStackId, op)  -- 记录操作
    sleep(200)
end

-- 撤销操作
print('\n撤销操作:')
local undoCount = 0
while not StackOps.isEmpty(undoStackId) and undoCount < 3 do
    local lastOp = StackOps.pop(undoStackId)
    undoCount = undoCount + 1
    print('撤销 ' .. tostring(undoCount) .. ':' .. tostring(lastOp))
    sleep(200)
end

print('剩余操作数:' .. tostring(StackOps.size(undoStackId)))

示例 5:多队列任务调度

local xfxModule = require('lib/XfxPlugin')
local xfx = xfxModule:new({apkName = 'xfxPlugin-release.apk'})

local QueueOps = xfx:getOps('queueOps')

if not QueueOps then
    error('无法获取 QueueOps 对象')
end

-- 创建多个优先级队列
local highPriorityQueue = 'highPriority'
local normalPriorityQueue = 'normalPriority'
local lowPriorityQueue = 'lowPriority'

QueueOps.create(highPriorityQueue)
QueueOps.create(normalPriorityQueue)
QueueOps.create(lowPriorityQueue)

-- 添加不同优先级的任务
QueueOps.enqueue(lowPriorityQueue, '低优先级任务1')
QueueOps.enqueue(normalPriorityQueue, '普通任务1')
QueueOps.enqueue(highPriorityQueue, '高优先级任务1')
QueueOps.enqueue(normalPriorityQueue, '普通任务2')
QueueOps.enqueue(lowPriorityQueue, '低优先级任务2')
QueueOps.enqueue(highPriorityQueue, '高优先级任务2')

-- 按优先级处理任务
print('按优先级处理任务:')
local processed = 0

-- 先处理高优先级
while not QueueOps.isEmpty(highPriorityQueue) do
    local task = QueueOps.dequeue(highPriorityQueue)
    processed = processed + 1
    print(string.format('[%d] 高优先级:%s', processed, task))
end

-- 再处理普通优先级
while not QueueOps.isEmpty(normalPriorityQueue) do
    local task = QueueOps.dequeue(normalPriorityQueue)
    processed = processed + 1
    print(string.format('[%d] 普通优先级:%s', processed, task))
end

-- 最后处理低优先级
while not QueueOps.isEmpty(lowPriorityQueue) do
    local task = QueueOps.dequeue(lowPriorityQueue)
    processed = processed + 1
    print(string.format('[%d] 低优先级:%s', processed, task))
end

print('所有任务处理完成,共处理 ' .. tostring(processed) .. ' 个任务')

示例 6:文件批量处理(队列 + 文件操作)

local xfxModule = require('lib/XfxPlugin')
local xfx = xfxModule:new({apkName = 'xfxPlugin-release.apk'})

local QueueOps = xfx:getOps('queueOps')
local FileOps = xfx:getOps('fileOps')

if not QueueOps or not FileOps then
    error('无法获取必要的 Ops 对象')
end

-- 创建文件处理队列
local fileQueueId = 'fileProcessQueue'
QueueOps.create(fileQueueId)

-- 定义要处理的文件目录
local sourceDir = '/sdcard/待处理文件'
local outputDir = '/sdcard/已处理文件'

-- 确保输出目录存在
if not FileOps.isDir(outputDir) then
    FileOps.createOrExistsDir(outputDir)
end

-- 获取源目录下的所有文件
local filesJson = FileOps.listFilesAsJson(sourceDir, '')
local files = jsonLib.decode(filesJson)

if files and #files > 0 then
    print('找到 ' .. tostring(#files) .. ' 个文件,加入处理队列')

    -- 将所有文件路径加入队列
    for i = 1, #files do
        local file = files[i]
        if file.filePath then
            QueueOps.enqueue(fileQueueId, file.filePath)
            print('加入队列:' .. file.fileName)
        end
    end

    -- 处理队列中的文件
    print('\n开始处理文件:')
    local processedCount = 0
    local failedCount = 0

    while not QueueOps.isEmpty(fileQueueId) do
        local filePath = QueueOps.dequeue(fileQueueId)
        if filePath then
            processedCount = processedCount + 1
            print(string.format('[%d] 处理文件:%s', processedCount, FileOps.getFileName(filePath)))

            -- 读取文件内容
            local content = FileOps.readFileToString(filePath)
            if content then
                -- 模拟处理:在内容前添加处理标记
                local processedContent = '[已处理] ' .. content

                -- 生成输出文件路径
                local fileName = FileOps.getFileName(filePath)
                local outputPath = outputDir .. '/' .. fileName

                -- 写入处理后的文件
                if FileOps.writeFileFromString(outputPath, processedContent) then
                    print('  处理成功:' .. fileName)
                else
                    print('  处理失败:无法写入 ' .. fileName)
                    failedCount = failedCount + 1
                end
            else
                print('  处理失败:无法读取文件')
                failedCount = failedCount + 1
            end

            sleep(100)  -- 模拟处理时间
        end
    end

    print(string.format('\n处理完成:成功 %d 个,失败 %d 个', processedCount - failedCount, failedCount))
else
    print('未找到待处理文件')
end

示例 7:文件操作历史记录(栈 + 文件操作)

local xfxModule = require('lib/XfxPlugin')
local xfx = xfxModule:new({apkName = 'xfxPlugin-release.apk'})

local StackOps = xfx:getOps('stackOps')
local FileOps = xfx:getOps('fileOps')

if not StackOps or not FileOps then
    error('无法获取必要的 Ops 对象')
end

-- 创建操作历史栈
local historyStackId = 'fileHistoryStack'
StackOps.create(historyStackId)

-- 定义工作目录
local workDir = '/sdcard/工作目录'
FileOps.createOrExistsDir(workDir)

-- 模拟文件操作序列
local function performOperation(operation, filePath, content)
    -- 记录操作到历史栈(格式:操作类型|文件路径|内容)
    local history = string.format('%s|%s|%s', operation, filePath, content or '')
    StackOps.push(historyStackId, history)
    print('执行操作:' .. operation .. ' -> ' .. FileOps.getFileName(filePath))
end

-- 创建文件1
local file1 = workDir .. '/file1.txt'
FileOps.writeFileFromString(file1, '这是文件1的初始内容')
performOperation('CREATE', file1, '这是文件1的初始内容')

sleep(200)

-- 创建文件2
local file2 = workDir .. '/file2.txt'
FileOps.writeFileFromString(file2, '这是文件2的初始内容')
performOperation('CREATE', file2, '这是文件2的初始内容')

sleep(200)

-- 修改文件1
FileOps.writeFileFromString(file1, '这是文件1的修改后内容')
performOperation('MODIFY', file1, '这是文件1的修改后内容')

sleep(200)

-- 创建文件3
local file3 = workDir .. '/file3.txt'
FileOps.writeFileFromString(file3, '这是文件3的内容')
performOperation('CREATE', file3, '这是文件3的内容')

print('\n操作历史记录数:' .. tostring(StackOps.size(historyStackId)))

-- 撤销操作(从栈顶开始)
print('\n开始撤销操作:')
local undoCount = 0
while not StackOps.isEmpty(historyStackId) and undoCount < 3 do
    local history = StackOps.pop(historyStackId)
    if history then
        local parts = {}
        for part in string.gmatch(history, '([^|]+)') do
            table.insert(parts, part)
        end

        if #parts >= 2 then
            local operation = parts[1]
            local filePath = parts[2]
            local fileName = FileOps.getFileName(filePath)

            undoCount = undoCount + 1
            print(string.format('撤销 [%d]:%s -> %s', undoCount, operation, fileName))

            -- 根据操作类型执行撤销
            if operation == 'CREATE' then
                -- 撤销创建:删除文件
                if FileOps.isFileExists(filePath) then
                    FileOps.delete(filePath)
                    print('  已删除文件:' .. fileName)
                end
            elseif operation == 'MODIFY' then
                -- 撤销修改:恢复为原始内容(这里简化处理,实际应该保存原始内容)
                print('  已恢复文件:' .. fileName)
            end
        end
    end
    sleep(200)
end

print('\n剩余操作数:' .. tostring(StackOps.size(historyStackId)))

示例 8:文件遍历和路径管理(队列 + 栈 + 文件操作)

local xfxModule = require('lib/XfxPlugin')
local xfx = xfxModule:new({apkName = 'xfxPlugin-release.apk'})

local QueueOps = xfx:getOps('queueOps')
local StackOps = xfx:getOps('stackOps')
local FileOps = xfx:getOps('fileOps')

if not QueueOps or not StackOps or not FileOps then
    error('无法获取必要的 Ops 对象')
end

-- 使用队列进行广度优先遍历(BFS)
local function bfsTraverse(rootDir)
    local dirQueueId = 'dirQueue'
    QueueOps.create(dirQueueId)

    -- 将根目录加入队列
    QueueOps.enqueue(dirQueueId, rootDir)

    local fileCount = 0
    local dirCount = 0

    print('开始广度优先遍历:' .. rootDir)

    while not QueueOps.isEmpty(dirQueueId) do
        local currentDir = QueueOps.dequeue(dirQueueId)
        if currentDir and FileOps.isDir(currentDir) then
            dirCount = dirCount + 1
            print('遍历目录:' .. currentDir)

            -- 获取当前目录下的所有文件和子目录
            local childrenJson = FileOps.listDirectChildrenAsJson(currentDir, true)
            local children = jsonLib.decode(childrenJson)

            if children then
                for i = 1, #children do
                    local child = children[i]
                    if child.filePath then
                        if FileOps.isDir(child.filePath) then
                            -- 子目录加入队列继续遍历
                            QueueOps.enqueue(dirQueueId, child.filePath)
                        else
                            -- 文件计数
                            fileCount = fileCount + 1
                            print('  文件:' .. child.fileName)
                        end
                    end
                end
            end
        end
    end

    print(string.format('\n遍历完成:目录 %d 个,文件 %d 个', dirCount, fileCount))

    -- 清理队列
    QueueOps.remove(dirQueueId)
end

-- 使用栈进行深度优先遍历(DFS)
local function dfsTraverse(rootDir)
    local dirStackId = 'dirStack'
    StackOps.create(dirStackId)

    -- 将根目录入栈
    StackOps.push(dirStackId, rootDir)

    local fileCount = 0
    local dirCount = 0

    print('\n开始深度优先遍历:' .. rootDir)

    while not StackOps.isEmpty(dirStackId) do
        local currentDir = StackOps.pop(dirStackId)
        if currentDir and FileOps.isDir(currentDir) then
            dirCount = dirCount + 1
            print('遍历目录:' .. currentDir)

            -- 获取当前目录下的所有文件和子目录
            local childrenJson = FileOps.listDirectChildrenAsJson(currentDir, true)
            local children = jsonLib.decode(childrenJson)

            if children then
                -- 将子目录逆序入栈(保证正序遍历)
                for i = #children, 1, -1 do
                    local child = children[i]
                    if child.filePath and FileOps.isDir(child.filePath) then
                        StackOps.push(dirStackId, child.filePath)
                    end
                end

                -- 处理文件
                for i = 1, #children do
                    local child = children[i]
                    if child.filePath and not FileOps.isDir(child.filePath) then
                        fileCount = fileCount + 1
                        print('  文件:' .. child.fileName)
                    end
                end
            end
        end
    end

    print(string.format('\n遍历完成:目录 %d 个,文件 %d 个', dirCount, fileCount))

    -- 清理栈
    StackOps.remove(dirStackId)
end

-- 执行遍历
local targetDir = '/sdcard/测试目录'
if FileOps.isDir(targetDir) then
    bfsTraverse(targetDir)
    dfsTraverse(targetDir)
else
    print('目录不存在:' .. targetDir)
end
1. 官方交流QQ群,添加多个不批。建议使用安卓手机或电脑申请。
飞云脚本圈: 586333520飞云脚本圈
Auto.js学习交流③群:286635606
Auto.js学习交流②群:712194666(满员)
IOS免越狱自动化测试群:691997586
2. 盗版,破解有损他人权益和违法作为,请各位会员支持正版。
3. 本站部分资源来源于用户上传和网络搜集,如有侵权请提供版权证明并联系站长删除。
4.如未特别申明,本站的技术性文章均为原创,未经授权,禁止转载/搬运等侵权行为。
5.全站所有付费服务均为虚拟商品,购买后自动发货。售出后概不接受任何理由的退、换。注册即为接受此条款。
6.如果站内内容侵犯了您的权益,请联系站长删除。
飞云脚本 » 【懒人精灵】小飞侠插件专题——栈和队列相关的操作

企业级大数据智能营销管理系统

源码转让