zoukankan      html  css  js  c++  java
  • 《剑指offer》5-使用2个栈实现队列【Java+Python】

    使用2个栈实现队列

    1. 题目描述
      用两个栈来实现一个队列,完成队列的Push和Pop操作。队列中的元素为int类型。

    2. 示例
      无 需要先明白2点:队列是先进先出的,栈是先进后出的

    3. 解题思路
      需要两个栈Stack1和Stack2,push的时候直接push进Stack1。pop需要判断Stack1和Stack2中元素的情况,Stack1空的话,直接从Stack2 pop,Stack1不空的话,把Stack1的元素push进入Stack2,然后pop Stack2的值。

    1.push: 直接push进stack1。需要pop全部stack2,才开始将stack1元素放进stack2中

    2.pop:if stack2 不为空,直接pop stack2;if stack2 为空,需要将stack1元素全部放入stack2中,然后pop

    1. Java实现
    import java.util.Stack;
     
    public class Solution {
        Stack<Integer> stack1 = new Stack<Integer>();
        Stack<Integer> stack2 = new Stack<Integer>();
        
        public void push(int node) {
            stack1.push(node);
            
        }
        
        public int pop() {
            if (stack1.isEmpty() && stack2.isEmpty()){
                return -1;
            }
            
            if (stack2.isEmpty()){
                while (!stack1.isEmpty()){
                    stack2.push(stack1.pop());
                }
            }
            return stack2.pop();
        
        }
    }
    
    1. Python实现
    # -*- coding:utf-8 -*-
    class Solution:
        def __init__(self):
            self.stack1 = []
            self.stack2 = []
            
        def push(self, node):
            # write code here
            self.stack1.append(node)
            
        def pop(self):
            # return xx
            if not self.stack1 and not self.stack2: 
                return 
            
            if not self.stack2: #如果stack2为空
                while self.stack1:
                    self.stack2.append(self.stack1.pop())
            return self.stack2.pop()   
    

    如果您觉得本文有用,请点个“在看”
    image.png

  • 相关阅读:
    ECMAScript 6 基础入门
    软件历史版本存档及下载
    arduino 编程基础
    生活中的实验 —— 家庭电路
    电子元件 —— 继电器
    电与磁 —— 电磁铁
    windows cmd 命令行 —— 进程与服务
    计算机硬件、摄影设备、物质、材料英语
    DHCP服务器备份、还原、迁移
    SVN同步
  • 原文地址:https://www.cnblogs.com/junge-mike/p/13509486.html
Copyright © 2011-2022 走看看