DAY 10 Stack and Queue Basic | 栈与队列:232.用栈实现队列 | 225. 用队列实现栈

Stack: Head in, tail out

Queue: Head in, head out

232. Implement Queue using Stacks:

To solve this problem. Implement two stacks. add the value into stack_in, when pop, move all the values into stack_out and then pop the last value (firsrt value in stack in). when push, pop, push, and pop. if anyvalue in stack_out, pop thoese values first because they went in first and need to go first.

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 None

        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:
        if self.stack_in or self.stack_out:
            return False
        return True

225. Implement Stack using Queues

To implemt stack using queue, move all 1 to n-1 elemts to the back of the list. then pop n.

class MyStack:

    def __init__(self):
        self.queue = deque()
        

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

    def pop(self) -> int:
        if self.empty():
            return None
        for i in range(len(self.queue)-1):
            self.queue.append(self.queue.popleft())
        return self.queue.popleft()

    def top(self) -> int:
        if self.empty() != None:
            return self.queue[-1]
        else:
            return None
        

    def empty(self) -> bool:
        print(self.queue)
        return not self.queue

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值