1. 程式人生 > >python中棧的線性表的實現

python中棧的線性表的實現

# 基於順序表技術實現棧類
class SStack:
    def __init__(self):
        self._elems = []

    def is_empty(self):
        return self._elems == []

    def top(self):
        '''
        取得棧中最後壓入的元素,不刪除
        :return:
        '''
        if self.is_empty():
            print('棧為空')
            return
        return self._elems[-1]

    def push(self, element):
        '''
        將元素壓入棧
        :param element:
        :return:
        '''
        self._elems.append(element)

    def pop1(self):
        '''
        刪除棧中最後壓入的元素
        :return:
        '''
        if self.is_empty():
            print('棧為空')
            return
        return self._elems.pop()


if __name__ == "__main__":
    test = SStack()
    test.push(1)
    test.push(2)
    print(test.is_empty())
    print (test.top())
    test.pop1()
    print(test.top())
    test.pop1()
    print(test.top())