认识队列

/* <队列> 1. 什么是队列 队列:两端“开口” 要求:只能从一端进入队列,另一端出队列 2.队头和队尾 队头:数据出队列的一端 队尾:数据进队列的一端 3.实现队列 1.顺序表:顺序队列 2.链表:链式队列 */
顺序队列

// [点击前往]-----了解这种方法的缺陷,以及解决方案 #include <stdio.h> // 进队函数 int eleIn(int* arr,int tail,int num) { arr[++tail] = num; printf("当前进入队列元素的值:%d\n", num); return tail; } // 出队(全部出队) void allOut(int* arr, int head, int tail) { while (head != tail) { printf("当前离开队列元素的值:%d\n", arr[head++]); } printf("当前离开队列元素的值:%d\n", arr[head++]); } int main() { int a[10]; // 定义数组,用于存储数据 int head = 0; int tail = -1; // 入队(进入5) tail = eleIn(a, tail, 1); tail = eleIn(a, tail, 2); tail = eleIn(a, tail, 3); tail = eleIn(a, tail, 4); tail = eleIn(a, tail, 5); printf("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n"); // 出队(全出去) allOut(a, head, tail); return 0; }
链式队列
#include <stdio.h> #include <stdlib.h> // 创建结点类型 typedef struct QNode { int data; struct QNode* pnext; }QNode; // 生成“头结点”的函数 createQueue() { QNode* temp = (QNode*)malloc(sizeof(QNode)); temp->data = 0; temp->pnext = NULL; return temp; } // 入队 eleIn(QNode* p, int num) // 参数:(尾指针,要存储的数据) { QNode* temp = (QNode*)malloc(sizeof(QNode)); temp->data = num; printf("当前进入队列元素的值:%d\n", num); temp->pnext = NULL; p->pnext = temp; p = temp; return p ; } // 出队 void eleOut(QNode* phead) { if (phead->pnext) // “头结点”存储的地址不为空 { QNode* temp = phead->pnext; // “头结点”后面的首元结点 printf("当前离开队列元素的值:%d\n", temp->data); phead->pnext = temp->pnext; free(temp); temp = NULL; } else { printf("队列为空!\n"); } // return ; } int main() { // 头指针和尾指针 QNode* phead = NULL; QNode* ptail = NULL; // “上面的两针”都指向生成的“头结点” phead = ptail = createQueue(); // 入队(进入5) ptail = eleIn(ptail, 1); ptail = eleIn(ptail, 2); ptail = eleIn(ptail, 3); ptail = eleIn(ptail, 4); ptail = eleIn(ptail, 5); printf("*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n"); // 出队(出去6) eleOut(phead); eleOut(phead); eleOut(phead); eleOut(phead); eleOut(phead); eleOut(phead); return 0; }
浙公网安备 33010602011771号