zoukankan      html  css  js  c++  java
  • 双栈模拟队列

    双栈模拟队列

    利用两个栈 S1、S2 模拟一个队列(如客户队列)时,如何用栈的运算实现队列的插入、 

    删除运算。使用算法描述。

    思路:

    • 输入:s1负责

    若s1非空,则直接输进s1。

    若s1满,则检查s2是否为空。

    若为空将s1元素反向置入s2中。若非空则失败(非空不能插入元素,否则破坏顺序)

    • 输出:s2负责

    若s2非空,则直接输出一个元素。

    若s2为空,需要从s1中调度。若s1也为空则失败。非空则调度后输出一个元素。

    #include <iostream>
    #include <stack>
    #include <string>
    using namespace std;
    
    #define max 1024
    #define ElemType int
    
    stack<ElemType> s1;
    stack<ElemType> s2;
    
    int Enqueue(ElemType x){
        //S1 栈满
        if(s1.size()==max){
            if(s2.empty()){
                //若s2为空,S1的内容反向搬到栈 S2
                while(!s1.empty()){
                    ElemType temp;
                    temp=s1.top();
                    s1.pop();
                    s2.push(temp);
                }//while
                s1.push(x);
                return 1;
            }//if s2
            else
    //            S1 栈满,S2 栈非空,则不可进行插入操作
                return 0;
            }
        //S1 栈不满,则直接进栈
        else{
            s1.push(x);
            return 1;
        }
    }
    
    int Dequeue(ElemType &x){
        //s2非空,直接输出
        if(!s2.empty()){
            x=s2.top();
            s2.pop();
            return 1;
        }
        //s2为空时需要从s1中调度
        else{
            if(!s1.empty()){
                while(!s1.empty()){
                    ElemType temp;
                    temp=s1.top();
                    s1.pop();
                    s2.push(temp);
                }
                x=s2.top();
                s2.pop();
                return 1;
            }
            else
                return 0;
        }
    }
    
    int main(){
        int arr[max];
        int n;
        while(cin>>n){
            cout<<"Input the arr"<<endl;
            for(int i=0;i<n;i++){
                cin>>arr[i];
                Enqueue(arr[i]);
            }
            cout<<"Function begins"<<endl;
            for(int i=0;i<n;i++){
                ElemType t;
                Dequeue(t);
                cout<<t<<endl;
            }
                
        }
        return 0;
    }
  • 相关阅读:
    ok6410 u-boot-2012.04.01移植六完善MLC NAND支持
    Apache XAMPP Fails to start under Windows XP
    Gridview导出到Excel
    PKU 1511 Invitation Cards (SPFA+邻接表)
    等待队列(二)
    HDU--杭电--1253--胜利大逃亡--广搜
    Java菜鸟学习笔记--Exception篇(一):异常简介
    jquery的DOM操作
    Windows下Postgre SQL数据库通过Slony-I 实现数据库双机同步备份
    POJ 2418 ,ZOJ 1899 Hardwood Species
  • 原文地址:https://www.cnblogs.com/DaiShuSs/p/11508359.html
Copyright © 2011-2022 走看看