如何用兩個棧實現一個隊列,兩個棧實現隊列

來源:互聯網
上載者:User

如何用兩個棧實現一個隊列,兩個棧實現隊列
How to use two stacks to implement a queue ?

今天看到的有意思的問題題,哇哢哢,簡直益智類哇~

"""Code writer : EOFCode date   : 2015.02.08Code file   : Queue_by_two_stack.pye-mail      : jasonleaster@163.comCode description :    How to implement a queue by two stack."""class Stack() :      S = []      def __init__(self, arg = []):          self.S = [len(arg)] + arg      def stack_empty(self) :          if self.S[0] == 0 :             return True          else :             return False      def push(self,x) :          self.S[0] += 1          if len(self.S) > self.S[0] :             self.S[self.S[0]] = x          else :                self.S = self.S + [x]          return self.S      def pop(self) :          if self.stack_empty() == True :             print "underflow"          else :                temp = self.S[0]                self.S[0] -= 1                return self.S[temp]       def show_stack(self) :          print "stack status:",self.S[1 : self.S[0] + 1]#---------------------------------------------------------------class Queue() :    def __init__(self, argv = []) :        self.s_1 = Stack()        self.s_2 = Stack()        for i in range(0, len(argv)) :            self.s_1.push(argv[i])    def is_empty(self) :        if  self.s_1.stack_empty() is True and \            self.s_2.stack_empty() is True :            return True        else :            return False    def enqueue(self, num) :        self.s_1.push(num)    def dequeue(self) :        if self.s_2.stack_empty() is True :            while self.s_1.stack_empty() is False :                self.s_2.push(self.s_1.pop())        if self.is_empty() is False :            return self.s_2.pop()#---------------------------------------------------------------"""Code below this is writed for testing :)"""Q = Queue([1,2,3,4,5])Q.enqueue(100)while Q.is_empty() is False :    print Q.dequeue(),

運行結果:







二零一五年攝於排雲閣 十字路口的陌生人

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.