赞
踩
typedef struct CircleIntQueue {
int data[TOTAL_SPACE];
int head;
int tail;
} *CircleIntQueuePtr;
CircleIntQueuePtr initQueue() {
CircleIntQueuePtr resultPtr = (CircleIntQueuePtr)malloc(sizeof(struct CircleIntQueue));
resultPtr->head = 0;
resultPtr->tail = 0;
return resultPtr;
}
void enqueue(CircleIntQueuePtr paraPtr, int paraValue) { //这里的+1 你可以具体带数字进行验证 //验证了你就会发现+1的作用 //%是防止数据超过规定的max 毕竟是个循环 if ((paraPtr->tail + 1) % TOTAL_SPACE == paraPtr->head) { printf("Queue full.\r\n"); return; } //合法存入 //尾巴++ paraPtr->data[paraPtr->tail % TOTAL_SPACE] = paraValue; paraPtr->tail++; }
int dequeue(CircleIntQueuePtr paraPtr) { int resultValue; //首先检查是否为空 if (paraPtr->head == paraPtr->tail) { printf("No element in the queue.\r\n"); return -1; } //删除头数据 //复制其值 resultValue = paraPtr->data[paraPtr->head % TOTAL_SPACE]; //head++ 删除其值 paraPtr->head++; return resultValue; }
void outputLinkQueue(CircleIntQueuePtr paraPtr) { int i; //检查是否为空 if (paraPtr->head == paraPtr->tail) { printf("Empty queue."); return; } printf("Elements in the queue: "); //循环打印 for (i = paraPtr->head; i < paraPtr->tail; i++) { printf("%d, ", paraPtr->data[i % TOTAL_SPACE]); //%的作用防止数大咯 } printf("\r\n"); }
void testLinkQueue() { int i = 10; CircleIntQueuePtr tempPtr = initQueue(); for (; i < 16; i ++) { enqueue(tempPtr, i); } outputLinkQueue(tempPtr); for (i = 0; i < 6; i ++) { printf("dequeue gets %d\r\n", dequeue(tempPtr)); } enqueue(tempPtr, 8); outputLinkQueue(tempPtr); } int main() { testLinkQueue(); return 1; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。