# include <stdio.h> # include <stdlib.h> # include <malloc.h>
typedef struct Queue { int* pBase; int front; int rear; }QUEUE, *PQUEUE;
void Init_Queue(PQUEUE pQ); bool En_Queue(PQUEUE pQ, int val); bool Out_Queue(PQUEUE pQ, int* pVal); bool Full_Queue(PQUEUE pQ); bool Empty_Queue(PQUEUE pQ); void Traverse_Queue(PQUEUE pQ);
int main(void) { PQUEUE Q; Q = (PQUEUE)malloc(sizeof(QUEUE)); if (Q == NULL) { printf("动态内存分配失败!\n"); return 1; } int val; Init_Queue(Q); En_Queue(Q, 1); En_Queue(Q, 2); En_Queue(Q, 3); En_Queue(Q, 4); En_Queue(Q, 5); En_Queue(Q, 6); En_Queue(Q, 7); Traverse_Queue(Q); if( Out_Queue(Q, &val) ) { printf("出队成功,出队的元素为:%d\n", val); } else { printf("出队失败!\n"); } Traverse_Queue(Q); free(Q); free(Q->pBase); return 0; }
void Init_Queue(PQUEUE pQ) {
pQ->pBase = (int*)malloc(sizeof(int) * 6); if(pQ->pBase == NULL) { printf("动态内存分配失败!\n"); } else { pQ->front = 0; pQ->rear = 0; } }
bool En_Queue(PQUEUE pQ, int val) { if( Full_Queue(pQ) ) { return false; } else { pQ->pBase[pQ->rear] = val; pQ->rear = (pQ->rear + 1) % 6; return true; } } bool Out_Queue(PQUEUE pQ, int* pVal) { if( Empty_Queue(pQ) ) { return false; } else { *pVal = pQ->pBase[pQ->front]; pQ->front = (pQ->front + 1) % 6; return true; } }
bool Empty_Queue(PQUEUE pQ) { if(pQ->rear == pQ->front) { return true; } else return false; }
bool Full_Queue(PQUEUE pQ) { if( (pQ->rear + 1) % 6 == pQ->front ) { return true; } else return false; }
void Traverse_Queue(PQUEUE pQ) { int i = pQ->front; while(i != pQ->rear) { printf("%d ", pQ->pBase[i]); i = (i + 1) % 6; } printf("\n"); return; }
|