实验题目:链队列的基本操作
• 【实验目的】
• 理解并掌握栈和队列的逻辑结构和存储结构;
• 理解栈和队列的相关基本运算;
• 编程对相关算法进行验证;
学会利用栈和队列解决实际问题
• 实验内容:编写一个程序,实现链队列的各种基本运算,并在此基础上设计一个主程序完成如下功能:
• (1)初始化队列q;
• (2)判断队列q是否为空;
• (3)依次进队列元素1,12,-10;
• (4)出队一个元素,并输出该元素;
• (5)输出队列的长度(元素个数);
• (6)依次进队元素13,-12,10;
• (7)输出队列长度;
• (7)输出出队序列。
头文件LinkQueue.h
#ifndef QUEUE_H_INCLUDED
#define QUEUE_H_INCLUDED
#include <bits/stdc++.h>
using namespace std; //cout,cin
//函数结果状态代码
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define QElemType int
//OVERFLOW 在 math.h 中已定义为3
typedef int Status;
typedef int Boolean; // 布尔类型
//为了操作的方便,建议本书每一个程序都把c1.h包含进去
typedef struct QNode
{
QElemType data;
struct QNode *next;
}QNode,*QueuePtr;
typedef struct
{
QueuePtr front,rear; /* 队头、队尾指针 */
}LinkQueue;
Status InitQueue (LinkQueue &Q);
Status QueueEmpty(LinkQueue Q);
int QueueLength(LinkQueue Q);
Status EnQueue (LinkQueue &Q,QElemType e);
Status DeQueue (LinkQueue &Q,QElemType &e);
#endif // LINKQUEUE_H_INCLUDED
LinkQueue.cpp
#include "LinkQueue.h"
#include <malloc.h>
#include <iostream>
using namespace std;
Status InitQueue(LinkQueue &Q)
{
Q.rear = Q.front = (QueuePtr)malloc(sizeof(QNode));
if(!Q.front)
exit (OVERFLOW);//存储分配失败
Q.front -> next = NULL;
return OK;
}
Status EnQueue(LinkQueue &Q,QElemType e)
{
QueuePtr p;
p = (QueuePtr)malloc(sizeof(QNode));
if(!p) exit (OVERFLOW);
p -> data = e;
p -> next = NULL;
Q.rear -> next = p;
Q.rear = p;
return OK;
}
Status DeQueue(LinkQueue &Q,QElemType &e)
{
QueuePtr p;
if (Q.front == Q.rear) return ERROR;
p = Q.front -> next;
e = p -> data;
Q.front -> next = p -> next;
if(Q.rear == p) Q.rear = Q.front;
free(p);
return OK;
}
Status QueueEmpty(LinkQueue Q)
{
if(Q.front==Q.rear)
return TRUE;
else
return FALSE;
}
int QueueLength(LinkQueue Q)
{
int i=0;
QueuePtr p;
p=Q.front;
while(Q.rear != p)
{
++i;
p = p -> next;
}
return i;
}
main.cpp
#include "LinkQueue.h"
#include <iostream>
using namespace std;
int main()
{
LinkQueue Q;
QElemType e;
cout << "①初始化队列Q"<< endl;
InitQueue(Q);
cout << "②判断队列Q是否为空"<< endl;
if(QueueEmpty(Q)) cout <<"空" << endl;
else cout << "不空" << endl;
cout << "③依次进队列元素1,12,-10";
EnQueue(Q,-1);
EnQueue(Q,2);
EnQueue(Q,10);
cout << endl;
cout << "④出队一个元素,并输出该元素:";
DeQueue(Q,e);cout << e <<endl;
cout << "⑤输出队列的长度:"<< QueueLength(Q)<< endl;
cout << "⑥依次进队元素13,12,10:";
EnQueue(Q,13);
EnQueue(Q,12);
EnQueue(Q,10);
cout << endl;
cout << "⑦输出出队序列:";
for(int i = 1;i <= 5;i++)
{
DeQueue(Q,e);
cout << e << " ";
}
cout << endl;
return 0;
}