棧 佇列 遞迴

2021-09-22 18:49:24 字數 3714 閱讀 3950

用陣列實現乙個順序棧

class

stack

:def

__init__

(self)

: self.items =

defisempty

(self)

:return self.items ==

defpush

(self, item)

:def

pop(self)

:return self.items.pop(

)def

peek

(self)

:return self.items[

len(self.items)-1

]def

size

(self)

:return

len(self.items)

用鍊錶實現乙個鏈式棧
class

node

:def

__init__

(self, data)

: self.data = data

self.

next

=none

class

stack

:def

__init__

(self)

: self.head =

none

defpush

(self, data)

:if self.head is

none

: self.head = node(data)

else

: new_node = node(data)

new_node.

next

= self.head

self.head = new_node

defpop(self)

:if self.head is

none

:return

none

else

: popped = self.head.data

self.head = self.head.

next

return popped

s = stack(

)s.push(1)

s.push(2)

s.pop(

)## 2

程式設計模擬實現乙個瀏覽器的前進、後退功能用陣列實現乙個順序佇列
class

queue

:def

__init__

(self)

: self.items =

defisempty

(self)

:return self.items ==

defenqueue

(self, item)

: self.items.insert(

0,item)

defdequeue

(self)

:return self.items.pop(

)def

size

(self)

:return

len(self.items)

用鍊錶實現乙個鏈式佇列
class

node

:def

__init__

(self, data)

: self.data = data

self.

next

=none

class

queue

:def

__init__

(self)

: self.front = self.rear =

none

defisempty

(self)

:return self.front ==

none

defenqueue

(self, item)

: temp = node(item)

if self.rear ==

none

: self.front = self.rear = temp

return

self.rear.

next

= temp

self.rear = temp

defdequeue

(self)

:if self.isempty():

return

temp = self.front

self.front = temp.

next

if(self.front ==

none):

self.rear =

none

return

str(temp.data)

實現乙個迴圈佇列
class

queue

:def

__init__

(self)

: front =

none

rear =

none

defenqueue

(q, value)

: temp = node(

) temp.data = value

if(q.front ==

none):

q.front = temp

else

: q.rear.link = temp

q.rear = temp

q.rear.link = q.front

defdequeue

(q):

if(q.front ==

none):

print

("queue is empty"

)return-1

value =

none

if(q.front == q.rear)

: value = q.front.data

q.front =

none

q.rear =

none

else

: temp = q.front

value = temp.data

q.front = q.front.link

q.rear.link = q.front

return value

def

fibonacci

(n):

if n ==

1or n ==2:

# print(1)

return

1elif n <1:

return-1

else

:return fibonacci(n-1)

+ fibonacci(n-2)

l_9 =

[fibonacci(n)

for n in

range(1

,10)]

print

(l_9)

# [1, 1, 2, 3, 5, 8, 13, 21, 34]

(2 1)遞迴 棧 佇列

題目 計算斐波那契數列 1 1 2 3 5 8 13 21 34 普通遞迴 include include include using namespace std const int max n 100 輸入 int n int x max n int fib int n intmain 記憶化搜尋...

遞迴 棧和佇列遍歷

import os def getalldir path,sp fileslist os.listdir path 得到當前目錄下所有的檔案 sp for filename in fileslist 處理每乙個檔案 fileabspath os.path.join path,filename if ...

python 遞迴(附利用棧和佇列模擬遞迴)

凡是迴圈能幹的事,遞迴都能幹12 34方法 1 寫出臨界條件 2 找這一次和上一次的關係 3 假設當前函式已經能用,呼叫自身計算上一次的結果再求出本次的結果 下面我們通過兩段 簡單看一下遞迴和非遞迴的區別 輸入乙個大於等於1的數,求1到n的和!1 普通函式方法 2 3 def hanshu n 4 ...