栈和队列以及深度遍历和广度遍历


具有先进后出的原则下面是用栈模拟的数据结构

stack = []
#压栈(向栈里存数据)存取的顺序是A,B,C
stack.append("A")
stack.append("B")
stack.append("C")
print(stack)
#出栈(从栈里取数据)按照顺序来由C到B再到A
res = stack.pop()
print(res)
print(stack)
res2 = stack.pop()
print(res2)
print(stack)

输出结果为

['A', 'B', 'C']
C
['A', 'B']
B
['A']

栈模拟递归遍历目录(深度遍历)先进后出

import os

def getAllDirDE(path):
    stack = []
    stack.append(path)


    #处理栈,当栈为空时,退出循环
    while len(stack) != 0:
    #从栈里取数据
    dirPath = stack.pop()
    #目录下所有的文件
    fileList = os.listdir(dirPath)
    #处理每一个文件
    for fileName in fileList:
        fileAbsPath - os.path.join(dirPath,fileName)
        if os.path.isdir(fileAbsPath):
            #是目录就压栈
            print("目录"+fileName)
            stack.append(fileAbsPath)
        else:
            print("普通"+fileName)


getAlDirDE(r"D:\qq文件\777777777")

队列
具有先进先出的原则,下面是队列模拟的数据结构

import collections
queue = collections.deque()
print(queue)
#进队
queue.append("A")
queue.append("B")
queue.append("C")
print(queue)
#出队
res = queue.popleft()
print(res)
print(queue)
res2 = queue.popleft()
print(res2)
print(queue)

输出结果为

deque([])
deque(['A', 'B', 'C'])
A
deque(['B', 'C'])
B
deque(['C'])

(广度遍历)先进先出

import os
import collections

def getAllDirQU(path):
    queue = collections.deque()
    #进队
    queue.append(path)

    while len(queue) != 0:
        #出队数据
        dirPath = queue.popleft()
        #找出所有文件
        fileList = os.listdir(dirPath)


        for fileName in fileList:
            #绝对路径
            fileAbsPath = os.path.join(dirPath,fileName)
            #判断是否是目录
            if os.path.isdir(fileAbsPath):
                print("目录"+ fileName)
                queue.append(fileAbsPath)
            else:
                print("普通文件:"+fileName)
    
    

getAllDirQU(r"D:\qq文件\7777777")

猜你喜欢

转载自blog.csdn.net/qq_41114516/article/details/83046432