AfxStd.h
#pragma once #ifndef AfxStd_H #define AfxStd_H #include<stdio.h> #include<stdlib.h> #include<string.h> #endif // !AfxStd
Queue.h
#pragma once #include"AfxStd.h" #ifndef Queue_H #define Queue_H typedef int ElemType; const int size= 10; struct Queue { int front; int rear; ElemType *data; int length; int capacity; }; void QueueInit(Queue &q); void QueueDestory(Queue &q); bool push(Queue &q, ElemType e); bool pop(Queue &q); int GetLength(Queue &q); bool QueueIncerment(Queue &q); bool QueueEmpty(Queue &q); ElemType GetFront(Queue &q); ElemType GetBack(Queue &q); void QueueClear(Queue &q); void QueuePrintf(Queue &q, void(*visit)(const void *)); void printI(const void * value); void printF(const void * value); void printC(const void * value); #endif // !Queue_H
Queue.cpp
#include"Queue.h" void QueueInit(Queue &q) { q.data = (ElemType*)malloc(sizeof(Queue)*size); q.front = q.rear =q.length = 0; q.capacity = size; } void QueueDestory(Queue &q) { free(q.data); q.data = NULL; q.front =q.rear =q.length = 0; q.capacity = size; } bool push(Queue &q,ElemType e) { if (q.length+1==q.capacity) { QueueIncerment(q); } q.data[q.rear] = e; q.rear = (q.rear + 1) % q.capacity; q.length++; return true; } bool pop(Queue &q) { if (q.length==0) { return false; } q.front = (q.front + 1) % q.capacity; q.length--; return true; } int GetLength(Queue &q) { return q.length; } bool QueueIncerment(Queue &q) { //ElemType *s = (ElemType *)malloc(sizeof(Queue)*(q.capacity+size)); /*扩容*/ ElemType *s = (ElemType *)realloc(q.data, sizeof(Queue)*(q.capacity*2)); if (s==NULL) { return false; } if (q.rear<q.front) { int i = 0; int j = q.capacity; while (i<q.rear) { s[j] = q.data[i]; i++; j++; } q.rear = q.length + q.rear+1; } q.data = s; q.capacity*= 2; return true; } bool QueueEmpty(Queue &q) { return q.length == 0; } ElemType GetFront(Queue &q) { if(!QueueEmpty(q)) { return q.data[q.front]; } return 0; } ElemType GetBack(Queue &q) { if (!QueueEmpty(q)) { return q.data[q.rear-1]; } return 0; } void QueueClear(Queue &q) { q.front = q.rear = q.length = 0; } void QueuePrintf(Queue &q, void(*visit)(const void *)) { if (visit == NULL) { return; } if (q.length == 0) { printf("空\n"); return; } int i = q.front; while (i != q.rear ) { visit(&q.data[i]); i = (i + 1) % q.capacity; } printf("\n"); } void printI(const void * value) { int *p = (int *)value; printf("%d\t", *p); } void printF(const void * value) { float *p = (float *)value; printf("%f\t", *p); } void printC(const void * value) { char *p = (char *)value; printf("%c\t", *p); }
main.cpp
#include"Queue.h" int main() { Queue q; QueueInit(q); for (int i=0;i<10;i++) { push(q,i); } QueuePrintf(q, printI); printf("\n%d %d %d %d\n", q.front, q.rear, q.capacity, q.length); for (int i = 0; i<5; i++) { pop(q); } QueuePrintf(q, printI); printf("\n%d %d %d %d\n", q.front, q.rear, q.capacity, q.length); for (int i = 0; i<22; i++) { push(q, i); } QueuePrintf(q, printI); printf("\n%d %d %d %d\n", q.front, q.rear,q.capacity, q.length); return 0; }