您的位置:首页 > 理论基础 > 数据结构算法

数据结构与算法分析(Java 语言描述)(35)—— 使用两个栈实现一个队列

2017-12-11 15:52 896 查看
思路:

当进行入队操作的时候

检查 stack_2 是否为空

若 stack_2 非空,将 stack_2 中的数据放入 stack_1 中

将需要入队的数据 push 到 stack_1 中

当进行出队操作的时候

检查 stack_1 是否为空

若 stack_1 非空,将 stack_1 的数据放入 stack_2 中

将 stakc_2 的栈顶元素 pop 出栈

大致的示意图



package com.dataStructure.queue;

import java.util.Stack;

public class UseStackToImplQueue {
private Stack<Integer> stack_1;
private Stack<Integer> stack_2;
private int count;
public UseStackToImplQueue(){
stack_1 = new Stack<>();
stack_2 = new Stack<>();
count = 0;
}

public void enqueue(int num){
//        if (stack_1.isEmpty() && stack_2.isEmpty()){
//            stack_1.push(num);
//        }else if (!stack_2.isEmpty()){
//            while (!stack_2.isEmpty()){
//                stack_1.push(stack_2.pop());
//            }
//            stack_1.push(num);
//        }

while (!stack_2.isEmpty()){
stack_1.push(stack_2.pop());
}
stack_1.push(num);
count++;
}

public int dequeue(){
//        if (!stack_2.isEmpty()){
//            return stack_2.pop();
//        }else {
//            while (!stack_1.isEmpty()){
//                stack_2.push(stack_1.pop());
//            }
//            return stack_2.pop();
//        }

while (!stack_1.isEmpty()){
stack_2.push(stack_1.pop());
}
count--;
return stack_2.pop();
}

public boolean isEmpty(){
return count == 0;
}

public static void main(String[] args){
UseStackToImplQueue queue = new UseStackToImplQueue();
queue.enqueue(6);
queue.enqueue(2);
queue.enqueue(1);
queue.enqueue(3);
queue.enqueue(5);
queue.enqueue(7);
while (!queue.isEmpty()){
System.out.print(queue.dequeue() + " ");
}

System.out.println();
System.out.println("----------------------------");

Stack<Integer> stack = new Stack<>();
stack.push(6);
stack.push(2);
stack.push(1);
stack.push(3);
stack.push(5);
stack.push(7);
while (!stack.isEmpty()){
System.out.print(stack.pop() + " ");
}

}

}


输出结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐