【数据结构】宜宾大学-计院-实验五

时间:2024-10-30 18:25:43
#include<iostream> #include<stdio.h> #include<stdlib.h> using namespace std; typedef int datatype; //节点成员变量的建立 typedef struct QNode { datatype data; struct QNode* Next; }QNode, *QueuePtr; //匿名结构体,成员变量为队列首尾指针 struct { QueuePtr front = NULL; QueuePtr rear = NULL; }Ptr; //开辟一个新节点 QNode* BuyNode(datatype x) { QNode* newnode = (QNode*)malloc(sizeof(QNode)); if (newnode == NULL) return NULL; else { newnode->data = x; newnode->Next = NULL; } return newnode; } //初始化头节点 void InitHead(QueuePtr head) { head = BuyNode(0); Ptr.front = head; Ptr.rear = head; } //销毁链式队列 void DestroyQueue(QueuePtr head) { QueuePtr pcur = head; while (pcur) { QueuePtr next = pcur->Next; free(pcur); pcur = next; } } //队列插入元素的实现(即入队列) void push(datatype x) { QueuePtr node = BuyNode(x); Ptr.rear->Next = node; Ptr.rear = node; } //队列元素的删除(即头删) void pop() { QueuePtr del = Ptr.front->Next; if (del == NULL) return; else { QueuePtr next = del->Next; Ptr.front->Next = next; free(del); del = NULL; } } //判空 bool EmptyQueue() { if (Ptr.front->Next == NULL) return true; else return false; } //获取队列首元素(即出队列) datatype GetHead() { if (Ptr.front->Next == NULL) return 0; else return Ptr.front->Next->data; } //队列当前元素个数 int SizeQueue() { int count = 0; QueuePtr pcur = Ptr.front->Next; while (pcur) { count++; QueuePtr next = pcur->Next; pcur = pcur->Next; } return count; } int main() { QueuePtr head = NULL; InitHead(head); push(1); push(2); push(3); push(4); push(5); push(6); push(7); push(8); cout << "队列中当前元素的个数:" << SizeQueue() << endl << endl; cout << "依次输出队列中所有元素:" << endl; while (!EmptyQueue()) { cout << GetHead() << " "; pop(); } cout << endl << endl; cout << "销毁队列:" << endl; DestroyQueue(head); cout << "销毁队列后队列中的元素个数:" << SizeQueue(); return 0; }