【数据结构】两个队列形成一个栈

栈和队列的相关函数
栈:https://blog.csdn.net/weixin_41892460/article/details/82973851
队列:https://blog.csdn.net/weixin_41892460/article/details/82973881

头文件

#ifndef __STACKBYTQ_H__
#define __STACKBYTQ_H__

#include"Queue.h"

typedef int DataType;

typedef struct StackByTwoQueue
{
	Queue q1;
	Queue q2;
}StackByTwoQueue;


void StackByTwoQueueInit(StackByTwoQueue* stq);
void StackByTwoQueueDestory(StackByTwoQueue* stq);
DataType StackByTwoQueueTop(StackByTwoQueue* stq);
int StackByTwoQueueEmpty(StackByTwoQueue* stq);
int StackByTwoQueueSize(StackByTwoQueue* stq);

void StackByTwoQueuePush(StackByTwoQueue* stq, DataType x);
void StackByTwoQueuePop(StackByTwoQueue* stq);

void TestStackByTwoQueue();


#endif

函数部分

#include  "StackByTQ.h"

void StackByTwoQueueInit(StackByTwoQueue* stq)
{
	assert(stq);
	QueueInit(&stq->q1);
	QueueInit(&stq->q2);
}
void StackByTwoQueueDestory(StackByTwoQueue* stq)
{
	assert(stq);
	QueueDestory(&stq->q1);
	QueueDestory(&stq->q2);
}

int StackByTwoQueueEmpty(StackByTwoQueue* stq)
{
	assert(stq);
	return QueueEmpty(&stq->q1) | QueueEmpty(&stq->q2);
}
int StackByTwoQueueSize(StackByTwoQueue* stq)
{
	assert(stq);
	return QueueSize(&stq->q1) + QueueSize(&stq->q2);
}

void StackByTwoQueuePush(StackByTwoQueue* stq, DataType x)
{
	assert(stq);
	if (QueueEmpty(&stq->q1) != 0)
	{
		QueuePush(&stq->q1, x);
	}
	else
	{
		QueuePush(&stq->q2, x);
	}
}


DataType StackByTwoQueueTop(StackByTwoQueue* stq)
{
	assert(stq);
	if (QueueEmpty(&stq->q1) != 0)
	{
		return stq->q1._back->_data;
	}
	else
	{
		return stq->q2._back->_data;
	}
}


void StackByTwoQueuePop(StackByTwoQueue* stq)
{
	assert(stq);
	Queue*empty = &stq->q1, *nonempty = &stq->q2;
	if (QueueEmpty(&stq->q1) != 0)
	{
		empty = &stq->q2;
		nonempty = &stq->q1;
	}
	while (QueueSize(nonempty) > 1)
	{
		QueuePush(empty, QueueFront(nonempty));
		QueuePop(nonempty);
	}
	QueuePop(nonempty);
}

测试

#include  "StackByTQ.h"




void TestStackByTwoQueue()
{
	StackByTwoQueue s;
	StackByTwoQueueInit(&s);
	StackByTwoQueuePush(&s, 1);
	StackByTwoQueuePush(&s, 2);
	StackByTwoQueuePush(&s, 3);
	StackByTwoQueuePush(&s, 4);
	StackByTwoQueuePush(&s, 5);
	while (StackByTwoQueueEmpty(&s))
	{
		printf("%d ", StackByTwoQueueTop(&s));
		StackByTwoQueuePop(&s);
	}
}


int main()
{
	TestStackByTwoQueue();
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_41892460/article/details/83013870