El funcionamiento básico de la cola en cadena con el nodo líder.
Tema:
Realice las operaciones de enqueue y dequeue de la cola en cadena.
Definición de interfaz de función:
Status QueueInsert(LinkQueue *Q,ElemType e);
Status QueueDelete(LinkQueue *Q,ElemType *e);
Entre ellos, Q y e son parámetros pasados por el usuario. La definición de tipo de LinkQueue es la siguiente:
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode * next;
}LNode,*LinkList;
typedef struct
{
LinkList front,rear; /* 队头、队尾指针 */
}LinkQueue;
Procedimiento de prueba de árbitro de muestra:
#include <stdio.h>
#include<malloc.h>
#define OK 1
#define ERROR 0
typedef int Status;
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode * next;
}LNode,*LinkList;
typedef struct
{
LinkList front,rear; /* 队头、队尾指针 */
}LinkQueue;
/* 带头结点的链队列的基本操作 */
Status InitQueue(LinkQueue *Q)
{
/* 构造一个空队列Q */
LinkList p;
p=(LNode*)malloc(sizeof(LNode));
p->next=NULL;
(*Q).rear=(*Q).front=p;
return OK;
}
Status List(LinkList L)
{
LinkList p;
if(!L) return ERROR;
p=L->next;
while(p)
{
printf(" %d",p->data);
p=p->next;
}
printf("\n");
return OK;
}
int QueueLenth(LinkQueue Q)
{
int n=0;
LinkList p;
if(Q.rear==Q.front)
return 0;
p=Q.front->next;
while(p)
{
n++;
p=p->next;
}
return n;
}
int main()
{
int x;
LinkQueue Q;
InitQueue(&Q);
QueueInsert(&Q,1);QueueInsert(&Q,2);QueueInsert(&Q,3);
List(Q.front );
QueueDelete( &Q,&x);
printf(" %d %d\n",x,QueueLenth(Q));
QueueDelete(&Q,&x);QueueDelete(&Q,&x);
printf(" %d %d\n",x,QueueLenth(Q));
return 0;
}
/* 请在这里填写答案 */
Ejemplo de salida:
Aquí se proporciona la salida correspondiente. Por ejemplo:
1 2 3
1 2
3 0
código:
Status QueueInsert(LinkQueue *Q,ElemType e){
LinkList p;
p=(LNode*)malloc(sizeof(LNode));//不要写new
p->data=e;
p->next=NULL;
Q->rear->next=p;
Q->rear=p;
return OK;
}
Status QueueDelete(LinkQueue *Q,ElemType *e){
if(Q->front==Q->rear) return ERROR;//所有都要写Q->front,不可以写Q.front
LinkList p;
p=Q->front->next;
*e=p->data;//不要漏了*,否则会输出地址
Q->front->next=p->next;
if(Q->rear==p) Q->rear=Q->front;
free(p);//不要写delete
return OK;
}