python 栈的基本操作
生活随笔
收集整理的這篇文章主要介紹了
python 栈的基本操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
本文為學習筆記,或許和某些視頻程序雷同。如有錯誤,請指正
棧的鏈表實現
列表的棧操作:
1、生成鏈表
2、入棧
3、出棧
4、返回棧頂元素
5、判斷是否為空棧
6、返回棧內元素個數
python中棧的操作函數(本例使用的函數):
append() : 尾部添加元素
pop():彈出尾部元素
python示例:
class Stack(): #定義類def __init__(self): #產生一個空的容器self.__list = []def push(self, item): #入棧self.__list.append(item)def pop(self): #出棧return self.__list.pop()def speek(self): #返回棧頂元素return self.__list[-1]def is_empty(self): #判斷是否已為空return not self.__listdef size(self): #返回棧中元素個數return len(self.__list)代碼測試:
if __name__ == '__main__':s = Stack()c = 1s.push('a')s.push('b')s.push(c)print('size:' + str(s.size()))print('speek:' + str(s.speek()))print(s.pop())print(s.pop())print(s.pop())print('size:' + str(s.size()))結果顯示:
size:3 speek:1 1 b a size:0總結
以上是生活随笔為你收集整理的python 栈的基本操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Web学习笔记】数据库连接池配置(DB
- 下一篇: 频率与波长的关系