10天【程式碼隨想錄演算法訓練營34期】 第五章 棧與佇列part01(● 232.用棧實現佇列 ● 225. 用佇列實現棧)

MiraMira發表於2024-03-29

232.用棧實現佇列

class MyQueue:

    def __init__(self):
        self.queue = []
        self.size = 0

    def push(self, x: int) -> None:
        self.queue.append(x)
        self.size += 1

    def pop(self) -> int:
        self.size -= 1
        return self.queue.pop(0)

    def peek(self) -> int:
        if self.size != 0:
            return self.queue[0]
        else:
            return None

    def empty(self) -> bool:
        if self.size == 0:
            return True
        else:
            return False

225. 用佇列實現棧

class MyStack:

    def __init__(self):
        self.stack_in = []
        self.stack_out = []
        self.size = 0

    def push(self, x: int) -> None:
        if self.stack_out:
            temp = self.stack_out.pop()
            self.stack_in.append(temp)
        self.stack_in.append(x)
        self.size += 1

    def pop(self) -> int:
        if self.stack_out:
            self.size -= 1
            return self.stack_out.pop(-1)
        elif self.stack_in:
            self.size -= 1
            return self.stack_in.pop(-1)

    def top(self) -> int:
        if self.stack_out:
            return self.stack_out[-1]
        else:
            temp = self.stack_in.pop(-1)
            self.stack_out.append(temp)
            return temp

    def empty(self) -> bool:
        if self.size == 0:
            return True
        else:
            return False

相關文章