用栈实现队列&&用队列实现栈

class MyQueue:

    def __init__(self):

       

        self.stack_in = []

        self.stack_out = []


 

    def push(self, x: int) -> None:

        self.stack_in.append(x)


 

    def pop(self) -> int:

        if self.empty():

            return 0

        if self.stack_out:

            return self.stack_out.pop()

        else :

            for i in range(len(self.stack_in)):

                self.stack_out.append(self.stack_in.pop())

            return self.stack_out.pop()

       


 

    def peek(self) -> int:

        ans=self.pop()

        self.stack_out.append(ans)

        return ans



 

    def empty(self) -> bool:

        return not (self.stack_in or self.stack_out)



 

# Your MyQueue object will be instantiated and called as such:

# obj = MyQueue()

# obj.push(x)

# param_2 = obj.pop()

# param_3 = obj.peek()

# param_4 = obj.empty()

 

class MyStack:

    def __init__(self):

        self.que = deque()

    def push(self, x: int) -> None:

        self.que.append(x)

    def pop(self) -> int:

        if self.empty():

            return None

        for i in range(len(self.que)-1):

            self.que.append(self.que.popleft())

        return self.que.popleft()

    def top(self) -> int:

       

        if self.empty():

            return None

        for i in range(len(self.que)-1):

            self.que.append(self.que.popleft())

        temp = self.que.popleft()

        self.que.append(temp)

        return temp

    def empty(self) -> bool:

        return not self.que

 

你可能感兴趣的:(python,开发语言)