利用順序儲存結構實現雙端佇列的入隊和出隊操作

qaz3171210發表於2015-02-11

標頭檔案:函式的宣告

#include <stdio.h>
#define QUEUESIZE 8
typedef char ElemType;
typedef struct DQueue
{
	ElemType queue[QUEUESIZE];
	int end1;
	int end2;
}DQueue;

int EnQueue(DQueue *DQ,ElemType e,int tag);
int DeQueue(DQueue *DQ,ElemType *e,int tag);


函式的定義

#include "雙端佇列.h"

int EnQueue(DQueue *DQ,ElemType e,int tag)
{
	switch(tag)
	{
	case 1:
		if(DQ->end1 != DQ->end2)
		{
			DQ->queue[DQ->end1] = e;
			DQ->end1 = (DQ->end1-1)%QUEUESIZE;
			return 1;
		}
		else
		{
			return 0;
		}
		break;
	case 2:
		if(DQ->end1 != DQ->end2)
		{
			DQ->queue[DQ->end2] = e;
			DQ->end2 = (DQ->end2+1)%QUEUESIZE;
			return 1;
		}
		else
		{
			return 0;
		}
		break;
	}
	return 0;
}

int DeQueue(DQueue *DQ,ElemType *e,int tag)
{
	switch(tag)
	{
	case 1:
		if((DQ->end1+1)%QUEUESIZE != DQ->end2)
		{
			DQ->end1 = (DQ->end1+1)%QUEUESIZE;
			*e = DQ->queue[DQ->end1];
			return 1;
		}
		else
		{
			return 0;
		}
		break;
	case 2:
		if((DQ->end2-1)%QUEUESIZE != DQ->end1)
		{
			DQ->end2 = (DQ->end2-1)%QUEUESIZE;
			*e = DQ->queue[DQ->end2];
			return 1;
		}
		else
		{
			return 0;
		}
		break;
	}
	return 0;
}


函式的應用

#include "雙端佇列.h"
//利用順序儲存結構實現雙端佇列的入隊和出隊操作
int main(void)
{
	DQueue Q;
	char ch;
	Q.end1 = 3;
	Q.end2 = 4;
	if(!EnQueue(&Q,'a',1))
	{
		printf("佇列已滿,不能入隊!");
	}
	else
	{
		printf("a左端入隊:\n");
	}
	if(!EnQueue(&Q,'b',1))
	{
		printf("佇列已滿,不能入隊!");
	}
	else
	{
		printf("b左端入隊:\n");
	}
		if(!EnQueue(&Q,'c',1))
	{
		printf("佇列已滿,不能入隊!");
	}
	else
	{
		printf("c左端入隊:\n");
	}
		if(!EnQueue(&Q,'d',2))
	{
		printf("佇列已滿,不能入隊!");
	}
	else
	{
		printf("d右端入隊:\n");
	}
		if(!EnQueue(&Q,'e',2))
	{
		printf("佇列已滿,不能入隊!");
	}
	else
	{
		printf("e右端入隊:\n");
	}
	printf("佇列左端出隊一次:");
	DeQueue(&Q,&ch,1);
	printf("%c\n",ch);
	printf("佇列左端出隊一次:");
	DeQueue(&Q,&ch,1);
	printf("%c\n",ch);
	printf("佇列右端出隊一次:");
	DeQueue(&Q,&ch,2);
	printf("%c\n",ch);
	printf("佇列右端出隊一次:");
	DeQueue(&Q,&ch,2);
	printf("%c\n",ch);
	return 0;
}


相關文章