随便写写。
#include<stdio.h>
#include<stdlib.h>
typedef struct QNode {
int data;
struct QNode *next;
}QNode,*QueuePtr;
typedef struct{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
//初始化
int InitQueue(LinkQueue &Q) {
Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
if (!Q.front) {
printf("空间开辟失败\n");
return 0;
}
Q.front->next = NULL;
}
//销毁队列
void DestoryQueue(LinkQueue &Q) {
while (Q.front) {
Q.rear = Q.front->next;
free(Q.front);
Q.front = Q.rear;
}
printf("销毁成功\n");
}
//插入
int EnQueue(LinkQueue &Q,int e) {
QueuePtr q;
q = (QueuePtr)malloc(sizeof(QNode));
if (!q) {
return 0;
}
q->data = e;
q->next = NULL;
Q.rear->next = q;
Q.rear = q;
}
//删除
void DeQueue(LinkQueue &Q) {
if (Q.front == Q.rear) {
printf("队列为空\n");
}
QueuePtr p;
p = (QueuePtr)malloc(sizeof(QNode));
p = Q.front->next;
Q.front->next = p->next;
if (Q.rear == p) {
Q.front == Q.rear;
}
}
//遍历
void QueueTraverse(LinkQueue Q) {
QueuePtr p;
p = (QueuePtr)malloc(sizeof(QNode));
if (Q.front == Q.rear) {
printf("队列为空\n");
}
else {
p = Q.front->next;
while (p) {
printf(" %d", p->data);
p = p->next;
}
printf("\n");
}
}
int main() {
LinkQueue Q;
InitQueue(Q);
for (int i = 0; i < 4; i++) {
EnQueue(Q, i);
}
QueueTraverse(Q);
DeQueue(Q);
QueueTraverse(Q);
DestoryQueue(Q);
QueueTraverse(Q);
return 0;
}
=======================分割线==========================
补发一个循环队列
#include<stdio.h>
#include<stdlib.h>
int max = 100;
typedef struct {
int *base;
int rear;
int front;
}SqQueue;
//初始化
void InitQueue(SqQueue &Q) {
Q.base = (int *)malloc(max * sizeof(int));
if (!Q.base) {
printf("空间开辟失败\n");
}
else {
Q.front = Q.rear = 0;
}
}
unsigned int QueueLength(SqQueue &Q) {
return (Q.rear - Q.front);
}
int EnQueue(SqQueue &Q,int e) {
if ((Q.rear + 1) % max == Q.front) {
return 0;
}
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % max;
}
void DeQueue(SqQueue &Q) {
if (Q.front != Q.rear) {
Q.front = (Q.front + 1) % max;
}
}
void TravelQueue(SqQueue &Q) {
int i=Q.front;
if (Q.front == Q.rear) {
printf("循环队列为空\n");
}
else {
for (i; i <Q.rear; i++) {
printf(" %d", Q.base[i]);
}
printf("\n");
}
}
int main() {
SqQueue Q;
InitQueue(Q);
for (int i = 0; i < 4; i++) {
EnQueue(Q, i);
}
TravelQueue(Q);
DeQueue(Q);
TravelQueue(Q);
return 0;
}