offer_05 用两个栈实现队列

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

#include<stdio.h>
#include<malloc.h>
typedef struct SqStack{
    int *top,*base;
    int stacksize;
}SqStack;

int InitStack(SqStack &S){
    S.base=(int *)malloc(20*sizeof(int));
    if(!S.base) return 0;
    S.top=S.base;
    S.stacksize=20;
    return 1;
    
}

void PushStack(SqStack &S,int e){
    if(S.top-S.base>=S.stacksize){
        S.base=(int *)realloc(S.base,(S.stacksize+10)*sizeof(int));
        if(!S.base)
    return;
    S.top=S.base+S.stacksize;
    S.stacksize+=10;
    }
    *S.top++=e;
    
}

int PopStack(SqStack &S,int &e){
    if(S.top==S.base)
    return 0;
    e=*--S.top;
    return 1;
}
int main(){
    SqStack S1,S2;
    InitStack(S1);
    InitStack(S2);
    int flag,num;
    printf("入队按1,出队按0!\n");
    while(~scanf("%d",&flag)){
        if(flag==1){
            int num;
            scanf("%d",&num);
            PushStack(S1,num);
            printf("入队%d\n",num);
        }else if(flag==0){
            int out,get=0;
            int result;
            result=PopStack(S2,out);
            if(result==0){
            //如果栈2没有数据,则把栈1所有数据进入到栈2 
            
                while(PopStack(S1,out)==1){
                PushStack(S2,out);
                get=1;
                
            }
            if(get==1){
                PopStack(S2,out);
               printf("出队列%d\n",out);
            }else
            printf("队列暂无数据!\n");
            
            
            }else if(result==1){
                printf("出队列%d\n",out);
            }
            
        }
    }
    
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 题目描述: · 用两个栈来实现一个队列,完成队列的入队(push)和出队(pop)操作。 队列中的元素为int类型...
    FloatingIsland阅读 981评论 0 0
  • 用两个栈实现队列: 用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。 思路:见...
    Buyun0阅读 1,176评论 0 0
  • 1.NSlog发布后不打印 #ifdef DEBUG//如果有DEBUG这个宏就编译下面一句代码 #define ...
    CocoLeo阅读 5,092评论 0 1
  • 我们单元的二楼养了一只狗,每当我们上来时,无论走路的声音大还是小,它都会汪汪的叫,我和妈妈在说话的时候,总会...
    小胡_804d阅读 1,410评论 0 0
  • “青藤杯”摄影征文大赛 一、活动主题:大学开学季,青春飞扬时(暂定) 摄影组:我与大学初见时 征文组:忆高中,绘...
    夏目清然阅读 4,340评论 0 9