实现:
/**********************************
两个队列实现栈
by Rowandjj
2014/7/21
**********************************/
#include<iostream>
using namespace std;
typedef struct _NODE_
{
int data;
struct _NODE_ *next;
}Node,*pNode;
typedef struct _QUEUE_
{
pNode pHead;
pNode pTail;
int size;
}Queue,*pQueue;
typedef struct _STACK_
{
Queue q1;
Queue q2;
}Stack,*pStack;
void InitQueue(pQueue pq)
{
pq->pHead = pq->pTail = (pNode)malloc(sizeof(Node));
if(!pq->pHead)
{
exit(-1);
}
pq->pHead->next = NULL;
pq->size = 0;
}
void Enqueue(pQueue pq,int data)
{
if(pq == NULL)
{
return;
}
pNode pNew = (pNode)malloc(sizeof(Node));
if(!pNew)
{
exit(-1);
}
pNew->data = data;
pNew->next = NULL;
pq->pTail->next = pNew;
pq->pTail = pNew;
pq->size++;
}
void Dequeue(pQueue pq,int* data)
{
if(pq == NULL)
{
*data = -1;
return;
}
pNode pDel = pq->pHead->next;
if(pDel != NULL)
{
*data = pDel->data;
pq->pHead->next = pDel->next;
if(pq->pTail == pDel)
{
pq->pTail = pq->pHead;
}
free(pDel);
pq->size--;
}
else
{
*data = -1;
return;
}
}
int QueueSize(Queue q)
{
return q.size;
}
void DestroyQueue(pQueue pq)
{
int data;
if(pq == NULL)
{
return;
}
while(pq->size > 0)
{
Dequeue(pq,&data);
}
free(pq->pHead);
}
void InitStack(pStack ps)
{
InitQueue(&ps->q1);
InitQueue(&ps->q2);
}
void Push(pStack ps,int data)
{
if(QueueSize(ps->q2) == 0)
{
Enqueue(&ps->q1,data);
}
else
{
Enqueue(&ps->q2,data);
}
}
int Pop(pStack ps)
{
int data;
if(QueueSize(ps->q1)==0 && QueueSize(ps->q2)==0)
{
return -1;
}
if(QueueSize(ps->q1) != 0)
{
while(QueueSize(ps->q1) != 1)
{
Dequeue(&ps->q1,&data);
Enqueue(&ps->q2,data);
}
Dequeue(&ps->q1,&data);
return data;
}
if(QueueSize(ps->q2) != 0)
{
while(QueueSize(ps->q2) != 1)
{
Dequeue(&ps->q2,&data);
Enqueue(&ps->q1,data);
}
Dequeue(&ps->q2,&data);
return data;
}
return -1;
}
void DestroyStack(pStack ps)
{
if(ps == NULL)
{
return;
}
DestroyQueue(&ps->q1);
DestroyQueue(&ps->q2);
}
int main()
{
int i,data;
Stack s;
InitStack(&s);
for(i = 0; i < 4; i++)
{
cin>>data;
Push(&s,data);
}
for(i = 0; i < 5; i++)
{
cout<<Pop(&s)<<endl;
}
DestroyStack(&s);
return 0;
}原文:http://blog.csdn.net/chdjj/article/details/38015287