1-5 带头结点的链队列的基本操作
分数 4
作者 黄复贤
单位 菏泽学院
实现链队列的入队列及出队列操作。
函数接口定义:
1 2 3
| Status QueueInsert(LinkQueue *Q,ElemType e);
Status QueueDelete(LinkQueue *Q,ElemType *e);
|
其中 Q 和 e 都是用户传入的参数。 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) { 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 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; }
|
需要注意当删除最后一个元素的时候要移动尾指针:
