力扣225用队列实现栈

 小编太不容易了,大家给小编点一点赞

typedef  int DataType;
typedef struct QNode
{
	struct QNode* next;
	DataType val;
}QNode;

typedef  struct Queue//避免老是传二级指针
{
	QNode* phead;
	QNode* tail;
	int size;
}Queue;


int QSize(Queue* p)
{
	assert(p);
	return p->size;
}

bool QueueEmpty(Queue* p)
{
	assert(p);
	if (p->size == 0)
		return true;
	else
		return false;
}


void QueueInit(Queue* p)
{
	assert(p);
	p->phead = p->tail = NULL;
	p->size = 0;
}

DataType QueueFront(Queue* p)
{
	assert(p);
	assert(p->phead);
	return p->phead->val;
}

DataType QueueBack(Queue* p)
{
	assert(p);
	assert(p->tail);
	return p->tail->val;
}
void QueueDestroy(Queue* p)
{
	assert(p);
	QNode* cur = p->phead;
	while (cur)
	{
		QNode* next = cur->next;
		free(cur);
		cur = next;
	}
	p->phead = p->tail = NULL;
	p->size = 0;
}

void Qpop(Queue* p)
{
	assert(p);
	assert(p->size);

	if (p->phead->next ==NULL)
	{
		free(p->phead);
		p->phead = p->tail = NULL;
	}
	else
	{
		QNode* next = p->phead->next;
		free(p->phead);
		p->phead = next;
	}
	p->size--;
}
//
typedef struct {
	Queue p1;
	Queue p2;
} MyStack;


MyStack* myStackCreate() {
	MyStack* pst = (MyStack*)malloc(sizeof(MyStack));
	QueueInit(&pst->p1);
	QueueInit(&pst->p2);
	return pst;
}

void QPush(Queue* p, DataType x)//插入先创建空间
{
	assert(p);
	QNode* newNode = (QNode*)malloc(sizeof(QNode));
	if (newNode == NULL)
	{
		printf("malloc failed");
		return;
	}
	newNode->next = NULL;
	newNode->val = x;

	if (p->phead == NULL)
	{
		p->phead = p->tail = newNode;
	}
	else
	{
		p->tail->next = newNode;
		p->tail = newNode;
	}
	p->size++;
}



void myStackPush(MyStack* obj, int x) {
	if (!QueueEmpty(&obj->p1))
	{
		QPush(&obj->p1, x);
	}
	else
	{
		QPush(&obj->p2,x);
	}
}

int myStackPop(MyStack* obj) 
{
	Queue* Empty = &obj->p1;
	Queue* NonEmpty = &obj->p2;
	if (!QueueEmpty(&obj->p1))
	{
		Empty = &obj->p2;
		NonEmpty = &obj->p1;
	}
	while (QSize(NonEmpty) > 1)
	{
		QPush(Empty, QueueFront(NonEmpty));
		Qpop(NonEmpty);
	}
	DataType top = QueueFront(NonEmpty);
	Qpop(NonEmpty);
	return top;
}

int myStackTop(MyStack* obj) {
	if (!QueueEmpty(&obj->p1))
	{
	return 	QueueBack(&obj->p1);
	}
	else
	{
	return 	QueueBack(&obj->p2);
	}
}

bool myStackEmpty(MyStack* obj) {
	return QueueEmpty(&obj->p1) && QueueEmpty(&obj->p2);
}

void myStackFree(MyStack* obj) {
	QueueDestroy(&obj->p1);
	QueueDestroy(&obj->p2);

	free(obj);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值