两个栈实现队列 两个队列实现栈

来源:互联网 发布:7.1声道测试软件 编辑:程序博客网 时间:2024/06/13 11:16

为说明思想,假设队列、栈都很大,不会出现满的情况。

1. 两个栈实现队列

栈的定义:

typedef struct node     //栈的结点结构{    int data;    struct node *next;}L,*Link;typedef struct{     //栈顶作链表的头部    Link  top;}S,*Stack;Stack init_stack();int push_stack(Stack s,int x);int pop_stack(Stack s,int &x);

实现一


思路

s1是入栈的,s2是出栈的。

入队列:直接压到s1是就行了

出队列:先把s1中的元素全部出栈压入到s2中,弹出s2中的栈顶元素;再把s2的所有元素全部压回s1

实现二

思路

 s1是入栈的,s2是出栈的。

入队列:直接压入s1即可

出队列:如果s2不为空,把s2中的栈顶元素直接弹出;否则,把s1的所有元素全部弹出压入s2中,再弹出s2的栈顶元素

比较

方法二入队列简单,出队列每个元素也只需转移一次。

参考代码:

void in_Queue(Stack s1, Stack s2, int x){    push_stack(s1, k);  // s1入栈}int out_Queue(Stack s1, Stack s2, int &x){    int x;    if(s2->top == NULL)     // s2为空时,把s1元素转移到s2    {        while(s1->top == NULL)        {            int t;            pop_stack(s1, &t);            push_stack(s2, t);        }    }    if(s2->top == NULL)     //转移后仍为空,则队列为空    {        printf("Empty!\n");        return 0;    }    pop_stack(s2, &x);      // s2不为空时直接出栈    return 1;}  

2. 两个队列实现栈

队列定义:

typedef struct node{    int data;    struct node *next;}L,*Link;typedef struct{     //定义一个队列    Link  front,rear;       //队头和队尾指针}Q,*Queue;Queue init_queue();int empty_quene(Queue q);int in_queue(Queue q,int x);int out_queue(Queue q,int &x);int size_queue(Queue q);

实现一



思路

q1是专职进出栈的,q2只是个中转站

入栈:直接入队列q1即可

出栈:把q1的除最后一个元素外全部转移到队q2,然后把刚才剩下q1中的那个元素出队列。之后把q2中的全部元素转移回q1

实现二

思路

    q1是专职进出栈的,q2只是个中转站。元素集中存放在一个栈中,但不是指定(q1q2)

    定义两个指针:pushtmp:指向专门进栈的队列q1tmp:指向临时作为中转站的另一个栈q2

入栈:直接入pushtmp所指队列即可。

出栈:把pushtmp的除最后一个元素外全部转移到队列tmp,然后把刚才剩下q1中的那个元素出队列

比较

实现二,出栈后就不用转移回原来的栈了(图示最后一步),这样减少了转移的次数。

参考代码

void push_stack(Queue q1, Queue q2, int x)      // x入栈{     if(!empty_queue(q1))    // 把x放入元素不为空的队列中     {         in_queue(q1, x);     }     else     {         in_queue(q2, x);     }}int pop_stack(Queue q1, Queue q2, int &x)   // 出栈顶元素到x{    Queue poptmp, tmp;    if(!empty_queue(q1))    {        poptmp = q1;    // poptmp指向可能不为空的队列        tmp = q2;       // tmp指向空的临时队列    }    else(!empty_queue(q2))    {        poptmp = q2;        tmp = q1;    }    if(empty_queue(poptmp))    {        printf("Stack Empty!\n");        return 0    }    else    {        while(size_queue(poptmp) != 1)  // 将poptmp的n-1个元素转移到临时队列中        {            int t;            out_queue(poptmp, &t);            in_queue(tmp, t);        }        out_queue(poptmp, &x);      // 出poptmp的最后一个元素        return 1;    }} 
0 0
原创粉丝点击