数据结构----栈与队列的相互转化(详通过栈实现一个队列)

两个栈实现一个队列

定义两个栈A、B实现一个队列先进先出的特点。

栈的特点:先进后出

队的特点:先进先出

需要注意的条件有:

1、队列满的条件

A满,B非空

2、队列空的条件

A空,B空

3、入队列,队列非满的条件

(1)A非满

(2)A满,B空(将A中的数据全部导入到B中)

4、出队列,队列非空的条件

(1)B中有数据

(2)A非空,B空(将A中的数据全部导入到B中)

queue.h

#ifndef __QUEUE_H
#define __QUEUE_H

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#define SIZE 5

typedef struct stack
{
	int *data;
	int top;
}Stack, *pStack;

typedef struct Que
{
	Stack sta;
	Stack stb;
}Que, *PQue;

void Init(pQue que);
void PushQue(pQue que, int val);

#endif

queue.c

#include "queue.h"

static void InitStack(pStack st)
{
	assert(st != NULL);

	st->data = (int *)malloc(sizeof(int)* SIZE);
	assert(st->data != NULL);

	st->top = 0;
}

static int IsEmptyStack(pStack st)
{
	assert(st != NULL);

	if (st->top == 0)
	{
		return 1;
	}

	return 0;
}

static int IsFullStack(pStack st)
{
	assert(st != NULL);

	if (st->top == SIZE)
	{
		return 1;
	}

	return 0;
}

void InitQue(pQue que)
{
	assert(que != NULL);

	InitStack(&que->sta);
	InitStack(&que->stb);
}

// 队列满:  sta满,并且stb非空
static int IsFullQue(pQue que)
{
	assert(que != NULL);

	if (IsFullStack(&que->sta) && !IsEmptyStack(&que->stb))
	{
		return 1;
	}

	return 0;
}

int IsEmptyQue(pQue que)
{
	assert(que != NULL);

	if (IsEmptyStack(&que->sta) && IsEmptyStack(&que->stb))
	{
		return 1;
	}

	return 0;
}

static void PushStack(pStack st, int val)
{
	assert(st != NULL);

	if (!IsFullStack(st))
	{
		st->data[st->top++] = val;
	}
}

static int GetTop(pStack st)
{
	assert(st != NULL);

	if (IsEmptyStack(st))
	{
		return -1;
	}

	return st->data[st->top - 1];
}

static int PopStack(pStack st)
{
	assert(st != NULL);

	if (IsEmptyStack(st))
	{
		return -1;
	}

	st->top--;

	return 1;
}

int PushQue(pQue que, int val)
{
	assert(que != NULL);

	if (IsFullQue(que))
	{
		return -1;
	}

	if (IsFullStack(&que->sta))
	{ 
		// 先将A中的数据全部导入到B中
		while (!IsEmptyStack(&que->sta))
		{
			int elem = GetTop(&que->sta);
			PopStack(&que->sta);
			PushStack(&que->stb, elem);
		}
	}

	PushStack(&que->sta, val);

	return 1;
}

int PopQue(pQue que)
{
	assert(que != NULL);

	if (IsEmptyQue(que))
	{
		return -1;
	}

	if (IsEmptyStack(&que->stb))
	{
		// 把A中的数据导入到B中
		while (!IsEmptyStack(&que->sta))
		{
			int elem = GetTop(&que->sta);
			PopStack(&que->sta);
			PushStack(&que->stb, elem);
		}
	}

	int elem = GetTop(&que->stb);
	PopStack(&que->stb);

	return elem;
}

两个队列实现一个栈

思想:

1、时刻保证一个队列是空的;

2、入栈时将数据插入到非空的队列中;

3、出栈时先将非空队列的前N-1个数据导入到空的队列中,再将最后一个数据输出;

4、判断栈满条件:非空的队列满;

5、判断栈空条件:两个队列都为空。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值