队列与栈作业(05次)
2018-04-16 本文已影响0人
crabor
队列
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ElemType int
#define QUEUE_SIZE 100
#define ARRAY_SIZE (QUEUE_SIZE+1)
#define MAX 20
typedef enum{YES=1,NO=0}Bool;
typedef enum{OK=1,ERROR=0}Status;
#define LINKED_QUEUE
#ifdef LINKED_QUEUE
typedef struct QNODE {
ElemType value;
struct QNODE *next;
} QNode;
typedef struct {
QNode *rear, *front;
} Queue;
Status CreateQueue(Queue **ppQueue) {
QNode *new;
int i;
new = (QNode *)malloc(sizeof(QNode));
if (new == NULL) {
return ERROR;
}
new->value = 0;
new->next = NULL;
*ppQueue=(Queue*)malloc(sizeof(Queue));
if(*ppQueue==NULL){
return ERROR;
}
(*ppQueue)->rear = new;
(*ppQueue)->front = new;
for (i = 0; i < QUEUE_SIZE; i++) {
new = (QNode *)malloc(sizeof(QNode));
if (new == NULL) {
return ERROR;
}
new->value = 0;
new->next = (*ppQueue)->front;
(*ppQueue)->front = new;
}
(*ppQueue)->rear->next = (*ppQueue)->front;
return OK;
}
int IsQueueFull(Queue *pQueue) {
return pQueue->rear->next->next == pQueue->front;
}
int IsQueueEmpty(Queue *pQueue) {
return pQueue->rear->next== pQueue->front;
}
Status Insert(Queue *pQueue, ElemType e) {
if (IsQueueFull(pQueue)) {
return ERROR;
}
pQueue->rear = pQueue->rear->next;
pQueue->rear->value = e;
return OK;
}
Status Delete(Queue *pQueue) {
if (IsQueueEmpty(pQueue)) {
return ERROR;
}
pQueue->front = pQueue->front->next;
return OK;
}
Status First(Queue *pQueue, ElemType *e) {
if (IsQueueEmpty(pQueue)) {
return ERROR;
}
*e = pQueue->front->value;
return OK;
}
#endif
#ifdef LOOP_QUEUE
typedef struct{
ElemType queue[ARRAY_SIZE];
int rear, front;
} Queue;
Status CreateQueue(Queue **pQueue){
*pQueue = (Queue *)malloc(sizeof(Queue));
if(*pQueue==NULL){
return ERROR;
}
(*pQueue)->rear = 0;
(*pQueue)->front = 1;
return OK;
}
int IsQueueFull(Queue *pQueue){
return (pQueue->rear + 2) % QUEUE_SIZE == pQueue->front;
}
int IsQueueEmpty(Queue *pQueue){
return (pQueue->rear + 1) % QUEUE_SIZE == pQueue->front;
}
Status Insert(Queue *pQueue,ElemType e){
if(IsQueueFull(pQueue)){
return ERROR;
}
pQueue->rear=(pQueue->rear+1)%QUEUE_SIZE;
pQueue->queue[pQueue->rear] = e;
return OK;
}
Status Delete(Queue *pQueue){
if(IsQueueEmpty(pQueue)){
return ERROR;
}
pQueue->front = (pQueue->front + 1) % QUEUE_SIZE;
return OK;
}
Status First(Queue *pQueue,ElemType *e){
if(IsQueueEmpty(pQueue)){
return ERROR;
}
*e = pQueue->queue[pQueue->front];
return OK;
}
#endif
int main(void){
Queue *p;
int i;
ElemType e;
ElemType ramElem;
CreateQueue(&p);
srand((unsigned)time(NULL));
for (i = 0; i < MAX;i++){
ramElem = rand() % 101;
Insert(p, ramElem);
printf("%d ", ramElem);
}
printf("\n");
First(p, &e);
printf("%d\n", e);
Delete(p);
First(p, &e);
printf("%d\n", e);
return 0;
}