博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
利用两个栈模拟一个队列
阅读量:3906 次
发布时间:2019-05-23

本文共 1062 字,大约阅读时间需要 3 分钟。

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

import java.util.Stack;public class Solution {
Stack
stack1 = new Stack
(); Stack
stack2 = new Stack
(); public void push(int node) {
stack1.push(node); } public int pop() {
//出队列 //判断当前栈是否为空,如果为空,直接抛出异常 if(stack1.isEmpty()&&stack2.isEmpty()){
throw new RuntimeException(); } int number; if(stack2.isEmpty()){
//只有当stack2为空的时候才可以让stack1中的元素进入stack2:原因是假如不加if判断,那么首先从stack1中入栈了两个两个 //元素进stack2,此时pop一个元素,符合队列的先进先出的原则,结果stack2中还有一个元素,如果这个时候再把stack1中的元素加入到stack2中,那么那个 //本来就还在stack2中的元素就被"压住了",而事实上,只有等它也出栈了才能让新的元素进栈。 while(!stack1.isEmpty()){
//如果stack1不为空,把stack1出栈,并且入stack2,相当于调换了一下顺序 number = stack1.pop(); stack2.push(number);//while循环可以就把所有的stack1中的元素放到了stack2当中。 } } return stack2.pop(); }}

push方法入栈,pop方法出栈,isempty判断一个栈是否为空。OVer!

转载地址:http://yrlen.baihongyu.com/

你可能感兴趣的文章
centos security & tuning
查看>>
Ext2 vs Ext3 vs Ext4
查看>>
linux fix superblock not found
查看>>
linux file System directory
查看>>
linux file System inode
查看>>
linux evaluate inode
查看>>
API monitor
查看>>
typeahead/autocomplete
查看>>
TernarySearchTree
查看>>
auto-complete
查看>>
codepen intro - frontend exercise
查看>>
system design questions
查看>>
电梯调度算法
查看>>
nginx debug
查看>>
tanchao
查看>>
lucent.net 分词
查看>>
SQLite vs MySQL vs PostgreSQL
查看>>
Web services nginx+php
查看>>
docker vs rtk
查看>>
mysql tuning
查看>>