zoukankan      html  css  js  c++  java
  • 剑指offer——用两个栈来实现队列

    用两个栈实现队列

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

    import java.util.Stack;
    
    public class Solution {
        Stack<Integer> stack1 = new Stack<Integer>();
        Stack<Integer> stack2 = new Stack<Integer>();
        
        public void push(int node) {
            
        }
        
        public int pop() {
        
        }
    }
    

      

     队列的特点:先入先出

    栈的特点:先入后出

    自己很笨的方法:在push时,就将stack中的元素进行重新整理,将stack中的元素顺序反过来,然后pop时,就直接出

    import java.util.Stack;
    
    public class Solution {
        Stack<Integer> stack1 = new Stack<Integer>();
        Stack<Integer> stack2 = new Stack<Integer>();
        
        public void push(int node) {
            if(!stack1.empty()){
                while(!stack1.empty()){
                    stack2.push(stack1.pop());
                }
                stack1.push(node);
                while(!stack2.empty()){
                    stack1.push(stack2.pop());
                }
            }else if(!stack2.empty()){
                while(!stack2.empty()){
                    stack1.push(stack2.pop());
                }
                stack2.push(node);
                while(!stack1.empty()){
                    stack2.push(stack1.pop());
                }
            }else{
                stack1.push(node);
            }
        }
        
        public int pop() {
            int res = 0;
            if(!stack1.empty()){
                res = stack1.pop();
            }else if(!stack2.empty()){
                res = stack2.pop();
            }
            return res;
        }
    }
    

      

    注:stack1和stack2哪个作为入栈那个作为出栈自己定

    别人的方法:

    用stack1来做入队列,不改变顺序,后入的放在上面

    当出队列时,若stack2为空,则把stack1中的全部出栈到stack2中,此时,顺序就反过来了,然后出栈,

    若stack2不为空,则直接出栈,此时stack1中的元素应该在stack2中最下面的元素的后面

    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.empty() && stack2.empty()){
                System.out.println("stack is empty");
            }
            if(stack2.empty()){
                while(!stack1.empty()){
                    stack2.push(stack1.pop());
                }
            }
            return stack2.pop();
        }
    }
    

      

  • 相关阅读:
    QTP最小化代码
    开源Web自动化测试框架
    翟志刚系电脑游戏高手
    Java开源框架集[转载]
    Windows xp 控制台命令一览表〔转载〕
    三大措施将SQL注入攻击的危害最小化
    Zee书评:对于涌的《软件性能测试与Load Runner实战》的个人看法
    藏獒遭主人打骂后咬舌自尽
    IDS\IPS相关知识〔搜集〕
    lr之RTE脚本(telnet方式访问水木清华)
  • 原文地址:https://www.cnblogs.com/SkyeAngel/p/8524913.html
Copyright © 2011-2022 走看看