zoukankan      html  css  js  c++  java
  • Java 用栈实现队列

            栈是先入后出,队列是先入先出。根据这个思想,可以用一个栈作为入队,另一个栈作为出队。只要把第一个栈的栈顶的元素压入第二个栈就好了,出队的时候输出第二个栈的栈顶,如果第二个栈的空了就需要不断操作从第一个栈的栈顶压入第二个栈,但是如果第一个栈也空了,那就说明所有元素都输出来了。

    import java.util.Stack;
    
    /**
     * 用栈实现队列
     * @author rhq
     *
     */
    public class StackQueue {
    
        // 作为入队序列
        private Stack<Integer> stack1 = new Stack<Integer>();
        // 作为出队序列
        private Stack<Integer> stack2 = new Stack<Integer>();
    
        public void push(int node) {
            // 入队时,要保证stack2为空
            while (!stack2.empty())
            {
                stack1.push(stack2.peek());
                stack2.pop();
            }
            stack1.push(node);
            System.out.println("入队元素是:" + stack1.peek());
        }
    
        public int pop() {
            // 出队时,要保证stack1为空
            while (!stack1.empty())
            {
                stack2.push(stack1.peek());
                stack1.pop();
            }
            System.out.println("出队元素是:" + stack2.peek());
            int temp = stack2.peek();
            stack2.pop();
            return temp;
        }
        
        public static void main(String[] args) {
            
            StackQueue so = new StackQueue();
            so.push(1);
            so.push(2);
            so.push(3);
    
            so.pop();
            so.pop();
            so.push(4);
            so.pop();
            so.push(5);
            so.pop();
            so.pop();
            
        }

    最终结果

    入队元素是:1
    入队元素是:2
    入队元素是:3
    出队元素是:1
    出队元素是:2
    入队元素是:4
    出队元素是:3
    入队元素是:5
    出队元素是:4
    出队元素是:5
  • 相关阅读:
    SP503 【PRINT
    UVA10924 【Prime Words】
    UVA902 【Password Search】
    UVA10339 【Watching Watches】
    UVA11057 【Exact Sum】
    DP题单解题报告合集
    P1829 [国家集训队]Crash的数字表格 / JZPTAB
    莫比乌斯反演入门
    莫比乌斯函数
    题解 P3168 [CQOI2015]任务查询系统
  • 原文地址:https://www.cnblogs.com/rinack/p/10037949.html
Copyright © 2011-2022 走看看