转【c语言】两个堆栈组成一个队列

假设有两个堆栈,分别是s1,s2,现在有数列“1,2,3,4,5”,要让这个数列实现先进先出的功能,也就是用两个堆栈组成一个队列,如何实现?

分析:

    先将数列压入栈s1,数列在栈中由顶到底的元素为“5,4,3,2,1”,再将数列压入栈s2,数列在栈中由顶到底的元素为“1,2,3,4,5”,如此出栈,则是“1,2,3,4,5”。

    必须注意,实现队列中的入队操作以及出队操作,并非如同上述操作那么直观。上述操作有一个前提,即两个栈都没有元素。而一般情况,s1和s2中都可能有元素或者没有元素。所以要抽象出更一般的入队以及出队操作。

    入队操作:先将s2中的所有元素出栈,再压入s1中,将要进栈的元素压入s1。

    出队操作:先将s1中的所有元素出栈,再压入s2,再从s2中出栈,则得到将要出队列的元素。

 

我的代码,简单实现,未包含所有的队列操作。

复制代码
#include <stdio.h>
#include <stdlib.h>



typedef struct NODE{
        struct NODE * next;
        int data;
}node;



typedef struct STACK{
        node * head;
        int len;
}stack;

typedef struct QUEUE{
        stack * fstack;
        stack * bstack;
}queue;


stack * init(void){
        stack * List=(stack *) malloc(sizeof(stack));
        List->head=NULL;
        List->len=0;
        return List;

}

int pop(stack *st){
        if(0>=st->len||NULL == st) {
                printf("NULL stack,leaving now\n");
                exit(1);
        }
        int pdata=st->head->data;
        st->head=st->head->next;
        st->len--;
        return pdata;
}

void push(stack *st, int n){
        if(NULL == st|| 0>st->len){
                printf("wrong stack,please check the source code, now leaving\n");
                exit(1);
        }
        node * pp=(node*)malloc(sizeof(node));
        pp->next=st->head;
        pp->data=n;
        st->head=pp;
        st->len++;
}

queue * init_queue(void){
        queue * qe=(queue*)malloc(sizeof(queue));
        stack *st1,*st2;
        st1=init();
        st2=init();
        qe->fstack=st1;
        qe->bstack=st2;
        return qe;
}

int  dequeue(queue * qe){
        int tmp;

        if (NULL ==qe ){printf("wrong in queue,now leaving\n");exit(1);}
        if(0==qe->fstack->len && 0==qe->bstack->len)
        {
                printf("no element in queue,now leaving \n");
                exit(1);
        }else if( 0==qe->fstack->len){/* qe->bstack->len != 0*/
                tmp=pop(qe->bstack);
                return tmp;
        }else{ /* qe->fstack ->len !=0 && qe->bstack->len !=0 */
                while(qe->fstack->len !=0){
                        tmp=pop(qe->fstack);
                        push(qe->bstack,tmp);
                }
                tmp=pop(qe->bstack);
                return tmp;
        }
}

void enqueue(queue * qe, int n){
                        int tmp;
        if( NULL == qe ){printf("NULL queue,wrong, now leaving \n");exit(1);}

        while(qe->bstack->len !=0){
                tmp=pop(qe->bstack);
                push(qe->fstack,tmp);
        }
        push(qe->fstack,n);
}



int main(){
        queue * qe=init_queue();

#if 1 /* test*/
        int n=5;
        while(n>0){
                enqueue(qe,n);
                n--;
        }
        int tmp=dequeue(qe);
        printf("%d\n",tmp);
        tmp=dequeue(qe);
        printf("%d\n",tmp);
#endif
        return 0;
}
复制代码
posted @ 2016-11-22 17:27  十日十乞  阅读(769)  评论(0编辑  收藏  举报