两个栈实现一个队列
定义两个栈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、判断栈空条件:两个队列都为空。