带头结点的链队列的基本操作 (10 分)

实现链队列的入队列及出队列操作。

函数接口定义:

Status QueueInsert(LinkQueue *Q,ElemType e);

Status QueueDelete(LinkQueue *Q,ElemType *e);

其中 Q 和 e 都是用户传入的参数。 LinkQueue 的类型定义如下:

typedef int ElemType; 
typedef struct LNode
{
    ElemType data;
	struct LNode * next;
}LNode,*LinkList;
typedef struct
 {
   LinkList front,rear; /* 队头、队尾指针 */
 }LinkQueue;

裁判测试程序样例:

#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;
}

/* 请在这里填写答案 */

输出样例:

在这里给出相应的输出。例如:

 1 2 3
 1 2
 3 0

答案如下:
这道题是有头结点的所以出的时候出的是头的下一个,编译器上报错而pta上是对的我也不知是为什么(迷)

Status QueueInsert(LinkQueue *Q, ElemType e)
{
	LinkList p;
	p = (LinkList)malloc(sizeof(LinkList));
	if (p == NULL)
	{
		return ERROR;
	}
	p->data = e;
	p->next = NULL;
	Q->rear->next = p;
	Q->rear = p;
	return OK;
}
Status QueueDelete(LinkQueue *Q, ElemType *e)
{
	LNode *p;
	p = Q->front->next;
	if (Q->front == Q->rear)
	{
		*e = -1;
		return ERROR;
	}
	Q->front->next = p->next;
	if (Q->rear->next =NULL )
	{
		Q->rear = Q->front;
	}
	*e = p->data;
	free(p);
	return OK;
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值