队列
#include<stdio.h>
#include<stdlib.h>
typedef int type;
typedef struct Node {
type data;
struct Node* next;
}Node;
typedef struct Queue {
struct Node* front;
struct Node* rear;
}Queue;
void QueueInit(Queue* p) {
p->front = p->rear = NULL;
}
struct Node* CreatNode(type x) {
Node* new =(struct Node*)malloc(sizeof(struct Node));
new->data = x;
new->next = NULL;
return new;
}
void QueuePush(Queue* p, type x) {
Node* node = CreatNode(x);
if (p->front == NULL) {
p->front = p->rear = node;
}else{
p->rear->next = node;
p->rear = node;
}
}
void QueuePop(Queue* p) {
if (p->front == NULL) {
return;
}
Node* next = p->front->next;
free(p->front);
p->front = next;
if (p->front == NULL) {
p->rear = NULL;
}
}
type QueueFront(Queue* p) {
return p->front->data;
}
type QueueRear(Queue* p) {
return p->rear->data;
}
int QueueSize(Queue* p) {
int num = 0;
Node* cur = p->front;
while (cur) {
num++;
cur = cur->next;
}
return num;
}
int QueueEmpty(Queue* p) {
if (p->front == NULL) {
return 1;
}
return 0;
}
void QueueDes(Queue* p){
Node* cur = p->front;
while (cur) {
cur->data = NULL;
cur->next = NULL;
free(cur);
cur = cur->next;
}
p->front = NULL;
p->rear = NULL;
}
int main() {
Queue p;
QueueInit(&p);
QueuePush(&p, 1);
QueuePush(&p, 2);
QueuePush(&p, 3);
QueuePush(&p, 4);
QueuePush(&p, 5);
int a = QueueFront(&p);
int b = QueueRear(&p);
printf("front = %d , rear = %d\n", a, b);
while (QueueEmpty(&p) != 1) {
printf("%d ", QueueFront(&p));
QueuePop(&p);
}
printf("\n");
return 0;
}