出入队算法为重点
重点就在于4个式子
// 循环队列
#include <stdio.h>
#include <malloc.h>
#define MAXSIZE 20
typedef struct
{
int data[MAXSIZE];
int front;
int rear;
}cque;
cque* initcque(cque* cq){
cq = (cque*)malloc(sizeof(cque));
cq->front = -1;
cq->rear = -1;
return cq;
}
int insert(cque* cq,int x){
if (cq->rear+1 % MAXSIZE == cq->front){
printf("queue Full!\n");
return 0;
}
cq->rear = (cq->rear+1)%MAXSIZE;
cq->data[cq->rear] = x;
return 1;
}
int delet(cque* cq){
if(cq->front == cq->rear){
printf("queue Null!\n");
return -1;
}
printf("delete %d\n",cq->data[cq->front+1]);
cq->front= (cq->front+1)%MAXSIZE;
return 1;
}
void display(cque* cq){
printf("\n***display***\n");
while(cq->front!=cq->rear){
printf("%d ",cq->data[cq->front+1]);
cq->front= (cq->front+1)%MAXSIZE;
}
}
重点理解两个结构体的含义
为什么需要单独的结构体存放front和rear?
// 链队列
#include<stdio.h>
#include<stdlib.h>
typedef int datatype;
typedef struct qnode
{
datatype data;
struct qnode *next;
}qnode;
typedef struct
{
qnode *front;
qnode *rear;
}linkque;
linkque* Initque()
{
linkque *q;
qnode *p;
q = (linkque*)malloc(sizeof(linkque));
p = (qnode*)malloc(sizeof(qnode));
p->next = NULL;
q->front = q->rear = p;
return q;
}
void inque(linkque *q,datatype x){
qnode *p;
p = (qnode*)malloc(sizeof(qnode));
p->data = x;
p->next = NULL;
q->rear->next=p;
q->rear = p;
}
int deleque(linkque *q){
//刚开始头尾都指向一个空,所以实际链表在front的下一个
qnode* t = q->front->next;
if(q->front==q->rear)
return 0;
printf("delete %d\n",t->data);
q->front->next=t->next;
//如果是最后一个
if(q->rear==t)
q->rear = q->front;
free(t);
return 1;
}
void display(linkque *q){
qnode *t=q->front->next;
while (t!=NULL)
{
printf("%d ",t->data);
t = t->next;
}
}