赞
踩
#pragma once #include<stdio.h> #include<stdlib.h> #include<assert.h> #include<stdbool.h> typedef int QListDataType; typedef struct QListNode { QListDataType val; struct QListNode* next; }QListNode; typedef struct Queue { QListNode* head; QListNode* tail; int size; }Queue; //初始化 void QueueInit(Queue* pq); //销毁 void QueueDestroy(Queue* pq); //队尾入队列 void QueuePush(Queue* pq, QListDataType x); //对头出队列 void QueuePop(Queue* pq); //获取队列头部元素 QListDataType QueueFront(Queue* pq); //获取队列队尾元素 QListDataType QueueBack(Queue* pq); //获取队列中有效元素个数 int QueueSize(Queue* pq); //检查队列是否为空,空返回真,非空返回假 bool QueueEmpty(Queue* pq);
#define _CRT_SECURE_NO_WARNINGS 1 #include"Queue.h" //初始化 void QueueInit(Queue* pq) { assert(pq); pq->head = NULL; pq->tail = NULL; pq->size = 0; } //销毁 void QueueDestroy(Queue* pq) { assert(pq); QListNode* cur = pq->head; while (cur) { QListNode* next = cur->next; free(cur); cur = next; } pq->head = NULL; pq->tail = NULL; pq->size = 0; } //队尾入队列 void QueuePush(Queue* pq, QListDataType x) { assert(pq); QListNode* newnode = (QListNode*)malloc(sizeof(QListNode)); if (newnode == NULL) { perror("malloc fail"); return; } newnode->val = x; newnode->next = NULL; if (pq->tail == NULL) { pq->head = pq->tail = newnode; } else { pq->tail->next = newnode; pq->tail = newnode; } pq->size++; } //队头出队列 void QueuePop(Queue* pq) { assert(pq); assert(pq->size); QListNode* tmp = pq->head->next; free(pq->head); pq->head = tmp; if (pq->head == NULL) pq->tail = NULL; pq->size--; } //获取队列头部元素 QListDataType QueueFront(Queue* pq) { assert(pq); assert(pq->size); return pq->head->val; } //获取队列队尾元素 QListDataType QueueBack(Queue* pq) { assert(pq); assert(pq->size); return pq->tail->val; } //获取队列中有效元素个数 int QueueSize(Queue* pq) { assert(pq); return pq->size; } //检查队列是否为空,空返回真,非空返回假 bool QueueEmpty(Queue* pq) { assert(pq); return pq->size == 0; }
#define _CRT_SECURE_NO_WARNINGS 1 #include"Queue.h" void Test1() { Queue q; Queue* pq = &q; //初始化 QueueInit(pq); QueuePush(pq, 1); printf("头部元素:%d 尾部元素:%d 队列中元素个数:%d\n", QueueFront(pq), QueueBack(pq),QueueSize(pq)); QueuePush(pq, 2); printf("头部元素:%d 尾部元素:%d 队列中元素个数:%d\n", QueueFront(pq), QueueBack(pq), QueueSize(pq)); QueuePush(pq, 3); printf("头部元素:%d 尾部元素:%d 队列中元素个数:%d\n", QueueFront(pq), QueueBack(pq), QueueSize(pq)); QueuePush(pq, 4); printf("头部元素:%d 尾部元素:%d 队列中元素个数:%d\n", QueueFront(pq), QueueBack(pq), QueueSize(pq)); QueuePop(pq); printf("头部元素:%d 尾部元素:%d 队列中元素个数:%d\n", QueueFront(pq), QueueBack(pq), QueueSize(pq)); QueuePop(pq); printf("头部元素:%d 尾部元素:%d 队列中元素个数:%d\n", QueueFront(pq), QueueBack(pq), QueueSize(pq)); QueuePop(pq); printf("头部元素:%d 尾部元素:%d 队列中元素个数:%d\n", QueueFront(pq), QueueBack(pq), QueueSize(pq)); QueuePop(pq); //printf("头部元素:%d 尾部元素:%d 队列中元素个数:%d\n", QueueFront(pq), QueueBack(pq), QueueSize(pq)); //销毁 QueueDestroy(pq); } int main() { Test1(); return 0; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。