棧和佇列以及深度遍歷和廣度遍歷
阿新 • • 發佈:2018-12-15
棧 具有先進後出的原則下面是用棧模擬的資料結構
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")