队列(单链表)
?
?
頭文件
#pragma once//利用帶頭節點的單鏈表實現隊列,隊頭為第一個數據節點typedef struct Node {int data;struct Node *next; }Node;//數據節點typedef struct HNode {struct Node *front;//隊頭指針struct Node *rear;//隊尾指針 }HNode,*PLQueue;//頭節點void InitQueue(PLQueue pl);//入隊 bool Push(PLQueue pl,int val);//獲取隊頭的值,但不刪除 bool GetTop(PLQueue pl,int *rtval);//獲取隊頭的值,且刪除 bool Pop(PLQueue pl,int *rtval);bool IsEmpty(PLQueue pl);void Destroy(PLQueue pl);cpp文件
#include <stdio.h> #include <assert.h> #include <stdlib.h> #include "lqueue.h" //利用帶頭節點的單鏈表實現隊列,隊頭為第一個數據節點void InitQueue(PLQueue pl) {assert(pl != NULL);pl->front = NULL;pl->rear = NULL; }//入隊 bool Push(PLQueue pl,int val) {Node *p = (Node *)malloc(sizeof(Node));p->data = val;p->next = NULL;if(IsEmpty(pl)){pl->front = p;pl->rear = p;}else{pl->rear->next = p;pl->rear = p;}return true; }//獲取隊頭的值,但不刪除 bool GetTop(PLQueue pl,int *rtval) {if(IsEmpty(pl)){return false;}if(rtval != NULL){*rtval = pl->front->data;}return true; }//獲取隊頭的值,且刪除 bool Pop(PLQueue pl,int *rtval) {if(IsEmpty(pl)){return false;}if(rtval != NULL){*rtval = pl->front->data;}Node *p = pl->front;pl->front = p->next;free(p);if(pl->front == NULL) //已經刪除最后一個節點{pl->rear = NULL;}return true; }bool IsEmpty(PLQueue pl) {return pl->front == NULL; }void Destroy(PLQueue pl) {Node *q;for(Node *p = pl->front;p->next != NULL;p = p-> next){q = p;free(q);}pl -> front = NULL;pl -> rear = NULL; }主函數
#include <stdio.h> #include "lqueue.h"int main() {HNode head;InitQueue(&head);for(int i=0;i<15;i++){Push(&head,i);}int tmp;while(!IsEmpty(&head)){Pop(&head,&tmp);printf("%d\n",tmp);}return 0; }?
總結
- 上一篇: 联想微型计算机电脑黑屏怎么做系统,联想电
- 下一篇: c语言创建一个hello.txt文件,并