棧 用python實現棧

2021-10-06 07:50:21 字數 3421 閱讀 3558

分別採用有序列表、單向鏈和雙向鏈實現棧的推入、彈出等功能。

方法一:有序列表的實現

# 直接利用python內建的list實現

class

stack

(object):

def__init__

(self)

: self.stack =

defpush

(self, item)

:def

peek

(self)

:if self.isempty():

raise indexerror(

"peek from empty stack"

)return self.stack[-1

]def

pop(self)

:if self.isempty():

raise indexerror(

"pop from empty stack"

)return self.stack.pop(

)def

isempty

(self)

:return self.stack ==

def__len__

(self)

:return

len(self.stack)

方法二:單鏈表的實現
class

node

(object):

def__init__

(self, value)

: self.value = value

self.

next

=none

def__repr__

(self)

:return self.value

class

stack

(object):

def__init__

(self)

: self.head =

none

defpush

(self, value)

: node = node(value)

if self.head is

none

: self.head = node

else

: node.

next

= self.head

self.head = node

defpop(self)

:if self.isempty():

raise indexerror(

"pop from empty stack"

)else

: node = self.head.value

self.head = self.head.

next

return node

defpeek

(self)

:if self.isempty():

raise indexerror(

"peek from empty stack"

)else

:return self.head.value

defisempty

(self)

:return self.head is

none

def__len__

(self)

: length =

0 current = self.head

while current:

length +=

1 current = current.

next

return length

方法三:雙鏈表的實現
class

node

(object):

def__init__

(self, value, prev=

none

,next

=none):

self.value = value

self.prev = prev

self.

next

=next

def__repr__

(self)

:return self.value

class

stack

(object):

def__init__

(self)

: self.head =

none

defpush

(self, value)

: new_node = node(value)

if self.isempty():

self.head = new_node

else

: new_node.

next

= self.head

self.head.prev = new_node

self.head = new_node

defpop(self)

:if self.isempty():

raise indexerror(

"pop from empty stack"

)else

: current = self.head

if current.

next

isnone

: self.head =

none

else

: current.

next

.prev =

none

self.head = current.

next

return current.value

defpeek

(self)

:if self.isempty():

raise indexerror(

"peek from empty stack"

)else

:return self.head

def__len__

(self)

: length =

0 current = self.head

while current:

length +=

1 current = current.

next

return length

defisempty

(self)

:return self.head is

none

用python實現棧 Python實現棧的方法

usr bin env python 定義乙個列表來模擬棧 stack def pu 出棧,用到了pop 函式 def popit if len stack 0 print cannot pop from an empty stack else print removed stack.pop 編歷棧...

用棧實現佇列 用佇列實現棧

棧的特點 filo firstinlastout 僅能從棧頂插入,刪除元素。最基本的介面包括push 從棧頂壓入元素 pop 從棧頂彈出元素 佇列的特點 fifo firstinfirstout 僅能從隊頭刪除元素,從隊尾插入元素。最基本的介面包括enque 從隊尾插入元素 deque 從隊頭刪除元...

用棧實現佇列,用佇列實現棧。好玩!!!

因為在資料結構中,棧和佇列長得實在是太像了,將他們拿來比較是不可避免的,棧 後進先出,而佇列 先進先出。同樣是只能在一端進行操作,那麼問題來了,能相互實現?能不能得好好分析一下嘛,如果是用兩個棧來實現佇列,好像這操作可以哦。一下,你就明白!顯然用兩個棧可以實現佇列的功能,就是借助另乙個棧來中轉一下,...