您的位置:首页 > 其它

用两个栈实现一个队列的功能

2013-11-01 09:23 507 查看
#include <iostream>

#include <stack>

using namespace std;

template <class T>

struct MyQueue

{

void push(T &t)

{

s1.push(t);

}

T font()

{

if(s2.empty())

{

if(s1.size() == 0)

throw;

while(!s1.empty())

{

s2.push(s1.top());

s1.pop();

}

}

return s2.top();

}

void pop()

{

if(s2.empty())

{

while(!s1.empty())

{

s2.push(s1.top());

s1.pop();

}

}

if(!s2.empty())

s2.pop();

}

stack<T> s1;

stack<T> s2;

};

int main()

{

MyQueue<int> mq;

int i;

for(i=1; i<=10; i++)

{

mq.push(i);

}

for(i=1; i<=10; i++)

{

cout << "出队:" << mq.font() << endl;

mq.pop();

}

return 0;

}

#include <iostream>

#include <stdio.h>

#include <string.h>

#include <conio.h>

using namespace std;

*****栈的存取规则是后进先出*****/

typedef struct student

{

int data;

struct student *next;

}node;

typedef struct stackqueue

{

node *bottom, *top;

}queue;

//初始化栈

queue *Initstackqueue(queue *HQ)

{

HQ->top = NULL;

HQ->bottom = NULL;

return HQ;

}

//入栈

queue *push(queue *HQ, int x)

{

node *s;

s = (node *)malloc(sizeof(node));

s->data = x;

s->next = NULL;

if(HQ->bottom == NULL)

{

HQ->bottom = s;

HQ->top = s;

}

else 

{

HQ->top->next = s;

HQ->top = s;

}

return HQ;

}

//出栈

int pop(queue *HQ)

{

node *p, *b;

int x;

if(HQ->bottom == NULL)

printf(" 已空\n");

else

{

b = HQ->bottom;  //栈底指针

p = HQ->top;     //栈顶指针

x = HQ->top->data;

if(HQ->bottom == HQ->top)

{

HQ->top = NULL;

HQ->bottom = NULL;

}

else

{

while(b->next != HQ->top)

{

b = b->next;

}

HQ->top = b;

HQ->top->next = NULL;

free(p);

}

}

//printf("移除:%d\n",x);

return x;

}

queue *queue_in(queue *hq_a, int x)

{

printf("入队:%d\n",x);

queue *hq;

hq = push(hq_a, x);

return hq;

}

int queue_out(queue *hq_a, queue *hq_b)

{

int temp, y;

if(hq_b->bottom != NULL)

{

while(hq_b->bottom != NULL)

{

y = pop(hq_b);

printf("出队:%d\n",y);

}

}

else

{

while(hq_a->bottom != NULL)

{

temp = pop(hq_a);

push(hq_b, temp);

}

while(hq_b->bottom != NULL)

{

y = pop(hq_b);

printf("出队:%d\n",y);

}

}

return 0;

}

int main()

{

queue *mystack_a, *mystack_b;

mystack_a = (queue *)malloc(sizeof(queue));

mystack_b = (queue *)malloc(sizeof(queue));

mystack_a = Initstackqueue(mystack_a);

mystack_b = Initstackqueue(mystack_b);

for(int i=1; i<=10; i++)

queue_in(mystack_a, i);

printf("\n");

for(int i=1; i<=10; i++)

queue_out(mystack_a, mystack_b);

return 0;

}



转发至微博
 



转发至微博
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: