2010-01-29 26 views
1

我想編寫一個類,它使用來自棧(帶單鏈表)的Push和Pop。我不知道如何編寫推送和彈出功能。我真的需要一個用Python編寫的簡單示例,並具有以下功能。Python中的單鏈表,如何編寫pop和push?

Push 
Pop 
ifEmpty 
+1

http://stackoverflow.com/questions/ 280243/python-linked-list Google上的第二個結果。 – Vince

+2

爲什麼使用鏈表? Python的內置列表非常適合這一點。 – Thomas

+4

http://docs.python.org/tutorial/datastructures.html#using-lists-as-stacks –

回答

8

the docs那迪諾福鏈接到:

的列表方法使它很容易 使用列表作爲堆棧,其中最後添加的 元素是第一要素 檢索( 「後進先出」)。到 添加一個項目到堆棧的頂部, 使用append()。要從 檢索堆棧頂部的項目,請使用pop() 而不顯示索引。對於 例如:

>>> stack = [3, 4, 5] 
>>> stack.append(6) 
>>> stack.append(7) 
>>> stack 
[3, 4, 5, 6, 7] 
>>> stack.pop() 
7 
>>> stack 
[3, 4, 5, 6] 
>>> stack.pop() 
6 
>>> stack.pop() 
5 
>>> stack 
[3, 4] 

最後,爲了check if a list is empty

>>> my_list = [] 
>>> not my_list 
True 
3

這裏是最簡單的Stack類:

class stack(list): 
    def push(self,item): 
     self.append(item) 
    def isEmpty(self): 
     return not self 

>>> a = stack() 
>>> a.push(1) 
>> a.isEmpty() 
False 
>>> a.pop() 
1 
>>> a.isEmpty() 
True