PTA(栈和队列)1-5 带头结点的链队列的基本操作

1-5 带头结点的链队列的基本操作

分数 4

作者 黄复贤

单位 菏泽学院

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

函数接口定义:

1
2
3
Status QueueInsert(LinkQueue *Q,ElemType e)

Status QueueDelete(LinkQueue *Q,ElemType *e)

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

1
2
3
4
5
6
7
8
9
10
typedef int ElemType; 
typedef struct LNode
{
ElemType data;
struct LNode * next;
}LNode,*LinkList;
typedef struct
{
LinkList front,rear; /* 队头、队尾指针 */
}LinkQueue;

裁判测试程序样例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#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
1 2
3 0

答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Status QueueInsert(LinkQueue *Q,ElemType e) {
// 实现队尾插入
LNode *newNode = (LNode*) malloc(sizeof (LNode));
newNode->data = e;
newNode->next = NULL;
Q->rear->next = newNode;
Q->rear = newNode;
return OK;
}

Status QueueDelete(LinkQueue *Q,ElemType *e) {
// 实现队头删除
if (Q->front == Q->rear) { // 现在是空栈
return ERROR;
}
LNode *p = Q->front->next; // 指向要删除的结点
*e = p->data;
Q->front->next = p->next;
// 如果删除的是最后一个结点,要改变尾指针
if (p == Q->rear) {
Q->rear = Q->front;
}
return OK;
}

需要注意当删除最后一个元素的时候要移动尾指针:

image-20251024150706695