欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python棧的基本定義與使用方法示例【初始化、賦值、入棧、出棧等】

 更新時(shí)間:2019年10月24日 09:48:07   作者:鯨落丶  
這篇文章主要介紹了python棧的基本定義與使用方法,結(jié)合實(shí)例形式分析了Python棧的初始化、賦值、入棧、出棧等相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了python棧的基本定義與使用方法。分享給大家供大家參考,具體如下:

# -*- coding:utf-8 -*-
#! python3
#在桟的設(shè)計(jì)中,我們需要定義一個(gè)實(shí)例屬性top。三個(gè)實(shí)例方法:獲取棧頂元素peek();出桟pop();入棧push()
#棧的效果:先進(jìn)后出
class Node(object):  ##節(jié)點(diǎn),包括兩個(gè)屬性,一個(gè)是節(jié)點(diǎn)的值,一個(gè)是節(jié)點(diǎn)的下一個(gè)指向
 def __init__(self,value):
  self.value = value   #賦值給節(jié)點(diǎn)
  self.next = None   #節(jié)點(diǎn)的下一個(gè)指向
class stack(object):
 def __init__(self):
  self.top = None    #創(chuàng)建棧,賦予top棧頂屬性,top初始為空
 def peek(self):     #獲取棧頂?shù)脑兀祷貙?duì)應(yīng)的值
  if self.top!= None:   #如果棧頂不為空,也就是說棧里有數(shù)據(jù)
   return self.top.value #那就直接返回棧頂?shù)闹?
  else:
   return None    #如果棧里無數(shù)據(jù),則返回None
 def push(self,node):    #添加元素到棧(參數(shù)包括self和節(jié)點(diǎn)的value,node)
  if node != None:    #如果加入的節(jié)點(diǎn),不為空
   packNode = Node(node)  #實(shí)例化Node類
   packNode.next = self.top #將新增的節(jié)點(diǎn)的指向賦值為棧頂?shù)闹赶?
   self.top = packNode   #將棧頂?shù)墓?jié)點(diǎn),賦值為新增節(jié)點(diǎn)
   return packNode.value  #返回節(jié)點(diǎn)的值
  else:
   return None    #返回None
 def pop(self):     #出棧
  if self.top == None:  #如果棧是空的
   return None    #返回None
  else:
   tmp = self.top.value  #將棧頂?shù)闹祩鹘otmp
   self.top = self.top.next #將棧頂指向變?yōu)槟壳皸m數(shù)南乱粋€(gè)節(jié)點(diǎn)
   return tmp     #返回出棧的節(jié)點(diǎn)的值
s = stack()
a = Node(1)
print(s.push(a).value)
print(s.push(2))
print(s.push(3))
print(s.peek())
print(s.push(4))
print(s.pop())
print(s.pop())
print(s.pop())
print(s.pop().value)

運(yùn)行結(jié)果:

1
2
3
3
4
4
3
2
1

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python加密解密算法與技巧總結(jié)》、《Python編碼操作技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python入門與進(jìn)階經(jīng)典教程

希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論