队列的链式结构
- 不带头结点
- 队空 Q.front == Q.rear == head
- 带头结点
- 队空 Q.front == Q.rear ==&第一个节点
#include<stdio.h>
#include<malloc.h>
typedef int ElemType;
typedef struct Node{
ElemType data;
struct Node *next;
}Node;
typedef struct{
Node *front;
Node *rear;
int length;
}Queue;
void init_queue(Queue *q){
q->front = q->rear =(Node *)malloc(sizeof(Node));
q->front->next = NULL;
q->length = 0;
}
void show(Queue *q){
if(q->front == q->rear){
printf("THE QUEUE IS EMPTY\n");
return ;
}
Node *p = q->front;
while(p < q->rear){
printf("%2d",p->data);
p = p->next;
}
printf("\n");
}
void push(Queue *q,ElemType e){
Node * p = (Node *)malloc(sizeof(Node));
q->rear->data = e;
q->rear->next = p;
q->rear = p;
q->length++;
}
void pop(Queue *q,ElemType *e){
if(q->front == q->rear){
printf("THE QUEUE IS EMPTY\n");
return ;
}
Node *p = q->front;
*e = p->data;
q->front = p->next;
q->length--;
//if(p == q->rear)
//q->rear = q->front;
free(p);
}
int main(){
Queue queue;
ElemType e;
init_queue(&queue);
push(&queue,2);
push(&queue,4);
show(&queue);
pop(&queue,&e);
show(&queue);
return 0;
}