C# · 12月 20, 2021

用两个栈实现队列-用连个队列实现栈

用两个栈实现队列

# -*- coding:utf-8 -*-

class Solution:

    def __init__(self):

        self.stackA=[]

        self.stackB=[]

    def push(self,node):

        # write code here

        self.stackA.append(node)

    def pop(self):

        # return xx

        if self.stackB:

            return self.stackB.pop()

        elif not self.stackA:

            return None

        else:

            while self.stackA:

                self.stackB.append(self.stackA.pop())

            return self.stackB.pop()

用连个队列实现栈

# -*- coding:utf-8 -*-

class Solution:

def __init__(self):

self.queueA=[]

self.queueB=[]

def push(self,node):

# write code here

if self.queueB:

self.queueB.append(node)

else:

self.queueA.append(node)

def pop(self):

# return xx

if self.queueB:

i = 1

length = len(self.queueB)

while self.queueB and i < length :

self.queueA.append(self.queueB.pop(0))

i += 1

return self.queueB.pop(0)

elif self.queueA :

i=1

length=len(self.queueA)

while self.queueA and i<length:

self.queueB.append(self.queueA.pop(0))

i+=1

return self.queueA.pop(0)

else:

return None