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

Python棧的實(shí)現(xiàn)方法示例【列表、單鏈表】

 更新時(shí)間:2020年02月22日 10:57:21   作者:授我以驢  
這篇文章主要介紹了Python棧的實(shí)現(xiàn)方法,結(jié)合實(shí)例形式分析了Python基于列表、單鏈表定義棧的相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例講述了Python棧的實(shí)現(xiàn)方法。分享給大家供大家參考,具體如下:

Python實(shí)現(xiàn)棧

  • 棧的數(shù)組實(shí)現(xiàn):利用python列表方法

代碼如下:

# 列表實(shí)現(xiàn)棧,利用python列表方法
class listStack(object):

  def __init__(self):
    self.items = []

  def is_empty(self):
    return self.items == 0

  def size(self):
    return len(self.items)

  def top(self):
    return self.items[len(self.items)-1]

  def push(self, value):
    return self.items.append(value)

  def pop(self):
    return self.items.pop()
if __name__ =="__main__":
  stack = listStack()
  stack.push("welcome")
  stack.push("www")
  stack.push("jb51")
  stack.push("net")
  print "棧的長(zhǎng)度:", stack.size()
  print "\n".join(['%s:%s' % item for item in stack.__dict__.items()]) #打印棧stack所有元素
  print "出棧:",stack.pop()
  print "出棧:",stack.pop()
  print "出棧:",stack.pop()

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

棧的長(zhǎng)度: 4
items:['welcome', 'www', 'jb51', 'net']
出棧: net
出棧: jb51
出棧: www

  • 棧的鏈表實(shí)現(xiàn):

棧的鏈表實(shí)現(xiàn)中,壓棧(push)類(lèi)似于在單鏈表中表頭添加節(jié)點(diǎn);出棧(pop)類(lèi)似于鏈表中表頭刪除節(jié)點(diǎn)并返回對(duì)應(yīng)節(jié)點(diǎn)值;棧頂元素(top)就是獲取鏈表中的第一個(gè)元素

鏈表節(jié)點(diǎn)的定義直接嵌套在鏈表?xiàng)n?lèi)中

代碼如下:

# 鏈表實(shí)現(xiàn)棧
class linkedStack(object):

  class Node(object):
    def __init__(self, value=None, next=None):
      self.value = value
      self.next = next

  def __init__(self):
    self.top = None
    self.length = 0

  def is_empty(self):
    return self.length == 0

  def size(self):
    return self.length

  # 獲取棧頂元素
  def get(self):
    if self.is_empty():
      raise Exception("Stack is empty!")
    return self.top.value

  # 壓棧
  def push(self, value):
    node = self.Node(value)
    old_top = self.top
    self.top = node
    node.next = old_top
    self.length += 1

  # 出棧
  def pop(self):
    if self.length == 0:
      raise Exception("Stack is empty!")

    item = self.top.value
    curnode = self.top.next
    self.top.next = self.top
    self.top = curnode
    self.length -= 1
    return item
if __name__ =="__main__":
  stack = linkedStack()
  stack.push("welcome")
  stack.push("www")
  stack.push("jb51")
  stack.push("net")
  print "棧的長(zhǎng)度:", stack.size()
  print "出棧:",stack.pop()
  print "出棧:",stack.pop()
  print "出棧:",stack.pop()
  print "出棧:",stack.pop()

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

棧的長(zhǎng)度: 4
出棧: net
出棧: jb51
出棧: www
出棧: welcome

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

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

相關(guān)文章

最新評(píng)論