数据结构---链式队列
基于链式存储结构实现的队列
实现方式:带头结点的单链表
操作:
(1)初始化
#include<stdio.h>
#include<stdlib.h>
//链式队列
//链表的结点结构
typedef struct Node
{int data;struct Node* next;
}QNode;
//声明队列结构(用结构体声明队列结构的好处是可以声明多个队列)
typedef struct queue
{QNode* head;QNode* tail;
}Queue;
//初始化
Queue* InitQueue()
{Queue *q = (Queue*)malloc(sizeof(Queue));if(q == NULL){printf("内存申请失败\n");return NULL;}QNode *p = (QNode*)malloc(sizeof(QNode));if(p == NULL){printf("内存申请失败\n");return NULL;}p->next = NULL;q->head = p;q->tail = p;return q;
}
(2)入队(使用带尾指针的尾插法)
//入队(尾插法)
Queue* push(Queue *q,int k)
{QNode* p = (QNode*)malloc(sizeof(QNode));if(p == NULL){printf("内存申请失败\n");return q;}p->data = k;p->next = q->tail->next;q->tail->next = p;q->tail = p;return q;
}
(3)出队
//出队
Queue* pop(Queue* q)
{if(q->head->next == NULL){printf("空队列\n");return q;}QNode* temp = q->head->next;q->head->next = q->head->next->next;if(temp == q->tail)//防止尾指针称为野指针{q->tail = q->head;}free(temp);temp = NULL;return q;
}
(4)判空
//判空
int isEmpty(Queue* q)
{if(q->head == q->tail){return 1; }return 0;
}
链式队列没有判满操作,是无限的
相比较于顺序队列,后面没有循环链式队列,
因为链式队列不存在假溢出的情况
除了链式队列和顺序队列还有优先队列和双端队列