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
  • 相关阅读:
    find 以及linux 和windows 文件互传
    27 关于Object类 -- equals()
    26 super关键字
    25 访问修饰符限定词
    24 继承 子类中方法重写
    23 static 关键字
    22 包(package)来解决不同包下同名文件的冲突问题
    21 封装(get,set方法)
    20 带参构造方法(this关键字)
    19 无参构造方法
  • 原文地址:https://www.cnblogs.com/rinack/p/10037949.html
Copyright © 2011-2022 走看看