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
 

你可能感兴趣的:(stack)