1. 程式人生 > >資料結構----通過兩個棧實現一個佇列

資料結構----通過兩個棧實現一個佇列

定義兩個棧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;
}