?? 5.4.c
字號:
//循環隊列的實現
//庫函數和常量定義:
#include <malloc.h>
#include <stdio.h>
#include <iostream.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
//(1)循環隊列存儲結構定義:
#define MAXQSIZE 100
typedef int Status;
typedef char QElemType;
typedef struct QNode{
QElemType data;
struct QNode *next;
}QNode,*QueuePtr;
typedef struct{
QElemType *base;
int front;
int rear;
}SqQueue;
//(2)構造一個空的循環隊列
Status InitQueue (SqQueue *Q)
{//構造一個空隊列Q
Q->base=(QElemType *)malloc(MAXQSIZE*sizeof(QElemType));
if (!Q->base) return ERROR;
Q->front=Q->rear=0;
return OK;
}
//(3)進隊算法實現:
Status EnQueue(SqQueue *Q,QElemType e)
{ //插入元素e為Q的新的隊尾元素
if ((Q->rear+1)%MAXQSIZE==Q->front)
//隊列滿
return ERROR;
Q->base[Q->rear]=e;
Q->rear=(Q->rear+1)%MAXQSIZE;
return OK;}
//(4)求隊列的長度算法
int QueueLengh(SqQueue Q){
//返回Q的元素個數,即隊列的長度
return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;
}
//(5)出隊操作算法
Status DeQueue(SqQueue *Q,QElemType *e)
{
//若隊列不空,則刪除Q的隊頭元素,用e返回其值,并返回OK;
//否則返回ERROR;
if (Q->front==Q->rear) return ERROR;
*e=Q->base[Q->front];
Q->front=(Q->front+1)%MAXQSIZE;
return OK;
}
//(6)遍歷隊列算法
Status QueueTraverse(SqQueue Q)
{ int p;
if (Q.front!=Q.rear)
{
p=Q.front;
printf("\n隊列中的內容為:");
while(p!=Q.rear)
{
printf("%c",Q.base[p] );
p=(p+1)%MAXQSIZE;
}
printf("\n");
return OK;
}
else return ERROR;}
//(7)清空隊列算法?
Status ClearQueue(SqQueue *Q){
//清空隊列Q
if (!Q->base) return (ERROR);
Q->front=Q->rear; //隊列為空
printf("隊列已清空!");
return OK;}
//(8)判隊列為空算法
Status QueueEmpty(SqQueue Q)
{
if (Q.front==Q.rear )
{
printf("隊列為空!\n");
return TRUE;
}
else return FALSE;
}
//(9)獲得隊列頭結點
Status GetHead(SqQueue Q,QElemType *e)
{
if (Q.front!=Q.rear ) {*e=Q.base[Q.front];return OK;}
else
{printf("sorry!Queue Empty!");return ERROR;}
}
void main()
{
SqQueue Q;QElemType e;
InitQueue (&Q);
EnQueue(&Q,'a');
EnQueue(&Q,'b');
EnQueue(&Q,'c');
EnQueue(&Q,'d');
QueueTraverse(Q);
QueueEmpty(Q);
QueueLengh(Q);
GetHead(Q,&e);
printf("頭結點:%c\n",e);
DeQueue(&Q,&e);
printf("%c已出隊\n",e);
ClearQueue(&Q);
QueueEmpty(Q);
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -