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