让阿豪来帮你解答,本回答参考chatgpt3.5编写提供,如果还有疑问可以评论或留言
Case:
Input:(输入的队列中有10、20、30、40、50这五个元素,2为待插入的元素)
5
10 20 30 40 50
2
Output:(由于在队首删除元素,所以先输出删除的队首元素为10,再执行一次后为20)
queue length is:5
elements in current queue:10 20 30 40 50
the front element has been deleted, it was 10
the front element has been deleted, it was 20
queue length is:4
now there are elements in queue: 30 40 50 2
the front element is now: 30
Solution:
链式队列的定义:
链式队列和普通的队列的定义很像,只不过把数组替换成了链表。
这个问题要求实现链式队列的基本操作,如进队,出队,求队列长度,清队等。
定义链式队列的结构体 QueueNode,结构体中定义了数据域 Data,并定义了一个结构体节点指针类型的队列指针 Rear,头指针 Front:
typedef int QElemType;
typedef struct QueueNode
{
QElemType Data;
struct QueueNode *Next;
}QueueNode; typedef struct LinkQueue { QueueNode * Front; QueueNode * Rear; }LinkQueue; 首先是判断队列为空的操作: int QueueEmpty(LinkQueue Q) { return (Q.Front == Q.Rear); } 再是求队列长度: int QueueLength(LinkQueue Q) { QueueNode *p = Q.Front; int num = 0; while(p != Q.Rear) { num++; p = p-> Next; } return num; } 然后是进队: int EnQueue(LinkQueue &Q, QElemType e) { QueueNode *pn = new QueueNode; pn->Data = e; pn->Next = NULL; Q.Rear->Next = pn; Q.Rear = pn; return 1; } 最后是出队: int DeQueue(LinkQueue &Q, QElemType & e) { if(QueueEmpty(Q)) { e = -1; return 0; } QueueNode *pn = Q.Front->Next; e = pn->Data; Q.Front->Next = pn->Next; if(Q.Rear == pn) Q.Rear = Q.Front; delete pn; return 1; } 由于出队的操作需要用到上一个队列节点,所以我们在队列顶加了一个空节点,0号位置没有节点。 需要注意的是,当出队列时,如果刚刚好删除了队尾,那么就要将 Rear 指针向前移一位,这样做的目的是避免节点的仍然存在造成的错误。 回到操作函数上,构造空队列函数需要申请一个空的链表: void InitQueue(LinkQueue &Q) { QueueNode *pn = new QueueNode; pn->Next = NULL; Q.Front = Q.Rear = pn; } 清空操作函数需要不断的出队: void ClearQueue(LinkQueue &Q) { int tmp; while(QueueLength(Q)) DeQueue(Q,tmp); } 判断链式队列是否满的操作在这里并不需要,因为链式队列的长度是可以动态的不断增长的。 最后是输出队列中的元素,其中 Traverse 需要一个函数指针作为参数: void Traverse(LinkQueue Q,void(*vi)(QElemType)) { QueueNode *p = Q.Front->Next; while(p != NULL) { vi(p->Data); p = p->Next; } } void f(QElemType d) { cout<<d<<" "; } 在Main函数中,先构造一个新队列: LinkQueue Q; InitQueue(Q); 再插入元素: while(cin>>n) EnQueue(Q,n); 这里要循环读入,因为我们是用while循环读入和插入数字的。 接下来可以输出了: printf("queue length is:%d\n",QueueLength(Q)); printf("elements in current queue: "); 然后是最重要的出队操作,在主函数中调用 DeQueue,由于 DeQueue 返回值为 0 时,说明队列已空,所以要做出判断: int res = DeQueue(Q,tmp); if(res == 0) printf("no elements.\n"); else printf("\nthe front element has been deleted, it was %d\n", tmp); 现在队列中有4个元素,再做一次出队操作: res= DeQueue(Q,tmp); if(res == 0) printf("no elements.\n"); else printf("\nthe front element has been deleted, it was%d\n", tmp); 再插入一个2: EnQueue(Q,2); 队列的长度以及队列中元素的个数: printf("queue length is:%d\n",QueueLength(Q)); printf("now there are elements in queue: "); Traverse(Q,f); printf("\n"); 最后输出队列头: GetHead(Q,tmp); printf("now the front element is:%d\n",tmp); 代码: