1. 程式人生 > >笨辦法學python3續 learn more python3 in hard way ex15-3 stack棧

笨辦法學python3續 learn more python3 in hard way ex15-3 stack棧

程式碼:

class StackNode(object):

    def __init__(self, value, nxt):
        self.value = value
        self.next = nxt

    def __repr__(self):
        nval = self.next and self.next.value or None
        return f"[{self.value}:{repr(nval)}]"


class Stack(object):
    def __init__(self):
        self.
top=None def push(self,obj): """push a new value to the top of the Stack """ # if self.top !=None: # node=StackNode(obj,self.top) # self.top=node # else: # node=StackNode(obj,None) # self.top=node ##簡便成 self.
top=StackNode(obj,self.top) def pop(self): """pops the value that is currently on the top of the stack """ if self.top: node=self.top self.top=node.next return node.value else: return None # def top(self):#重名報錯 # """returns a reference to the first item,does not remove """
# return self.top!=None and self.top.value or None def first(self): """Returns a *reference* to the first item, does not remove.""" return self.top != None and self.top.value or None def count(self): """count the numbers of elements in the stack """ count=0 node=self.top while node: count +=1 node=node.next return count def dump(self,mark="------"): print(mark,end=" ") node=self.top while node: print(node,end=" ") node=node.next print() colors = Stack() colors.push("Cadmium Red Light") print(colors.first()) colors.push("Hansa Yellow") print(colors.dump("test")) print(colors.first()) colors.push("Pthalo Green") print(colors.first())

自動化測試:

from Stack import *

def test_push():
    colors = Stack()
    colors.push("Pthalo Blue")
    assert colors.count() == 1
    colors.push("Ultramarine Blue")
    assert colors.count() == 2

def test_pop():
    colors = Stack()
    colors.push("Magenta")
    colors.push("Alizarin")
    assert colors.pop() == "Alizarin"
    assert colors.pop() == "Magenta"
    assert colors.pop() == None

def test_top():
    colors = Stack()
    colors.push("Cadmium Red Light")
    assert colors.first() == "Cadmium Red Light"
    colors.push("Hansa Yellow")
    assert colors.first() == "Hansa Yellow"
    colors.push("Pthalo Green")
    assert colors.first() == "Pthalo Green"

程式碼中兩處註釋: 1.原來是這樣想的 棧和單鏈表很像 按照單鏈表的原理,這樣打的 zed修改過的是個遞迴 重複操作top.next=next 2.顯示棧頂元素 的方法名叫top()原來 self.top 會有bug 換了個名字

原理: 在這裡插入圖片描述 在這裡插入圖片描述

出棧: 在這裡插入圖片描述 在這裡插入圖片描述