两个队列实现栈

原理:
假设有两个队列Q1和Q2,当二者都为空时,入栈操作可以用入队操作来模拟,可以随便选一个空队列,假设选Q1进行入栈操作,现在假设a,b,c依次入栈了(即依次进入队列Q1),这时如果想模拟出栈操作,则需要将c出栈,因为在栈顶,这时候可以考虑用空队列Q2,将a,b依次从Q1中出队,而后进入队列Q2,将Q1的最后一个元素c出队即可,此时Q1变为了空队列,Q2中有两个元素,队头元素为a,队尾元素为b,接下来如果再执行入栈操作,则需要将元素进入到Q1和Q2中的非空队列,即进入Q2队列,出栈的话,就跟前面的一样,将Q2除最后一个元素外全部出队,并依次进入队列Q1,再将Q2的最后一个元素出队即可。

实现:

/**********************************
两个队列实现栈
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;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值