這篇文章將為大家詳細(xì)講解有關(guān)Python怎么實(shí)現(xiàn)棧,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

使用Python 實(shí)現(xiàn)棧。
兩種實(shí)現(xiàn)方式:
基于數(shù)組 - 數(shù)組同時(shí)基于鏈表實(shí)現(xiàn)
基于單鏈表 - 單鏈表的節(jié)點(diǎn)時(shí)一個(gè)實(shí)例化的node 對(duì)象
完整代碼可見GitHub:
https://github.com/GYT0313/Python-DataStructure/tree/master/5-stack
目錄結(jié)構(gòu):
注:一個(gè)完整的代碼并不是使用一個(gè)py文件,而使用了多個(gè)文件通過(guò)繼承方式實(shí)現(xiàn)。
arraycollection.py
""" File: abstractcollection.py Author: Ken Lambert """ class AbstractCollection(object): """An abstract collection implementation.""" # Constructor def __init__(self, sourceCollection = None): """Sets the initial state of self, which includes the contents of sourceCollection, if it's present.""" self._size = 0 if sourceCollection: for item in sourceCollection: self.add(item) # Accessor methods def isEmpty(self): """Returns True if len(self) == 0, or False otherwise.""" return len(self) == 0 def __len__(self): """Returns the number of items in self.""" return self._size def __str__(self): """Returns the string representation of self.""" return "[" + ", ".join(map(str, self)) + "]" def __add__(self, other): """Returns a new bag containing the contents of self and other.""" result = type(self)(self) for item in other: result.add(item) return result def __eq__(self, other): """Returns True if self equals other, or False otherwise.""" if self is other: return True if type(self) != type(other) or \ len(self) != len(other): return False otherIter = iter(other) for item in self: if item != next(otherIter): return False return True
abstractstack.py
""" File: abstractstack.py Author: Ken Lambert """ from abstractcollection import AbstractCollection class AbstractStack(AbstractCollection): """An abstract stack implementation.""" # Constructor def __init__(self, sourceCollection = None): """Sets the initial state of self, which includes the contents of sourceCollection, if it's present.""" AbstractCollection.__init__(self, sourceCollection) # Mutator methods def add(self, item): """Adds item to self.""" self.push(item)2. 基于數(shù)組
運(yùn)行示例:
代碼:
棧實(shí)現(xiàn):arraystack.py
""" File: abstractstack.py Author: Ken Lambert """ from abstractcollection import AbstractCollection class AbstractStack(AbstractCollection): """An abstract stack implementation.""" # Constructor def __init__(self, sourceCollection = None): """Sets the initial state of self, which includes the contents of sourceCollection, if it's present.""" AbstractCollection.__init__(self, sourceCollection) # Mutator methods def add(self, item): """Adds item to self.""" self.push(item)
數(shù)組實(shí)現(xiàn):arrays.py
""" File: arrays.py An Array is a restricted list whose clients can use only [], len, iter, and str. To instantiate, use <variable> = array(<capacity>, <optional fill value>) The fill value is None by default. """ class Array(object): """Represents an array.""" def __init__(self, capacity, fillValue = None): """Capacity is the static size of the array. fillValue is placed at each position.""" self._items = list() for count in range(capacity): self._items.append(fillValue) def __len__(self): """-> The capacity of the array.""" return len(self._items) def __str__(self): """-> The string representation of the array.""" return str(self._items) def __iter__(self): """Supports iteration over a view of an array.""" return iter(self._items) def __getitem__(self, index): """Subscript operator for access at index.""" return self._items[index] def __setitem__(self, index, newItem): """Subscript operator for replacement at index.""" self._items[index] = newItem3. 基于鏈表
運(yùn)行示例:
代碼:
linkedstack.py
"""
linkedstack.py
"""
from node import Node
from abstractstack import AbstractStack
class LinkedStack(AbstractStack):
"""基于單鏈表實(shí)現(xiàn)棧-鏈表頭部為棧頂"""
def __init__(self, source_collection=None):
self._items = None
AbstractStack.__init__(self, source_collection)
def __iter__(self):
"""迭代-使用一個(gè)列表實(shí)現(xiàn), 列表第一項(xiàng)為單鏈表的最后一項(xiàng)"""
def visit_nodes(node):
if node != None:
visit_nodes(node.next)
temp_list.append(node.data)
temp_list = []
visit_nodes(self._items)
return iter(temp_list)
def peek(self):
"""返回棧頂元素"""
self._prior_condition()
return self._items.data
def clear(self):
"""清空列表"""
self._size = 0
self._items = None
def push(self, item):
"""入棧"""
self._items = Node(item, self._items)
self._size += 1
def pop(self):
"""出棧"""
self._prior_condition()
old_item = self._items.data
self._items = self._items.next
self._size -= 1
return old_item
def _prior_condition(self):
if self._size == 0:
raise KeyError("The stack is empty.")node.py
""" 鏈表結(jié)構(gòu)的節(jié)點(diǎn)類 """ class Node(object): def __init__(self, data, next=None): self.data = data self.next = next
關(guān)于“Python怎么實(shí)現(xiàn)棧”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。
標(biāo)題名稱:Python怎么實(shí)現(xiàn)棧-創(chuàng)新互聯(lián)
本文網(wǎng)址:http://www.chinadenli.net/article2/dgedoc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供響應(yīng)式網(wǎng)站、網(wǎng)站設(shè)計(jì)公司、網(wǎng)頁(yè)設(shè)計(jì)公司、網(wǎng)站排名、電子商務(wù)、品牌網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容