TAoCP 2.2.2 - 2.2.3 :Stack (棧)

Stack (棧)

 

操作限制在push和pop(最多還有top)的linear list(線性表)。

 

暫時只有鏈表實現,數組實現也不難,自己寫寫看吧~

 

 

#! /usr/bin/env python3
# coding:utf-8

class StackError(Exception): pass
class StackOverFlow(StackError): pass
class StackUnderFlow(StackError): pass


class Node:

    def __init__(self, data, next=None):
        self.data = data
        self.next = next


class Stack:

    def __init__(self):
        self.top = None

    def is_empty(self):
        return self.top == None

    def push(self, node):
        if node == None:
            raise StackOverFlow

        node.next = self.top
        self.top = node

    def pop(self):  
        if self.is_empty():
            raise StackUnderFlow

        item = self.top
        data = item.data

        self.top = item.next
        del item

        return data
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章