#include<iostream>
#include<math.h>
using namespace std;
#define SIZE 10
#pragma warning(disable:4996)
typedef struct l
{
char data;
struct l* next;
}node;
typedef struct I
{
node *front;
node *rear;
}List;
void openlist(List &L);//初始化队列
void insertlist(List &L, char a);//入队
void outlist(List &L);//出队
int getlength(List L);//获取队列长度
char gettop(List L);//获取队列头的元素
void destorylist(List &L);//销毁队列A方法
void Destorylist(List &L);//销毁队列B方法
int main()
{
char a;
char x;
List L; openlist(L);
while (1)
{
cout << "请输入进队元素";
cin >> a;
insertlist(L, a);
cout << "是否继续录入(Y/N)?";
cin >> x;
if (x == 'N')break;
}
cout << "此时队列长为:" << getlength(L) << endl;
cout << "此时队列头元素为:" << gettop(L) << endl;
while (L.front != L.rear)outlist(L);
cout << "此时队列长为:" << getlength(L) << endl;
destorylist(L);
return 0;
}
void openlist(List &L)//初始化队列
{
L.front = L.rear = new node;
if (!L.front)cout << "ERROR" << endl;
else L.front->next = NULL;
}
void insertlist(List &L, char a)//入队
{
cout << "入队元素为:" << a ;
node *p = new node;
p->data = a;
p->next = NULL;
L.rear->next= p;
L.rear = p;
}
void outlist(List &L)//出队
{
if(L.rear==L.front)cout<< "队已空,无元素可以出队" << endl;
else
{
node *p = L.front->next;
cout << "出队元素为:" << p->data << endl;
L.front->next = p->next;
if (L.rear == p)L.rear = L.front;
delete p;
}
}
int getlength(List L)//获取队列长度
{
int count=0;
node *p = L.front;
while (p != L.rear)
{
p = p->next;
count++;
}
return count;
}
char gettop(List L)//获取队列头的元素
{
if (L.front == L.rear)cout << "ERROR" << endl;
return L.front->next->data;
}
void destorylist(List &L)//销毁队列A方法
{
while (L.front)
{
L.rear = L.front->next;
delete L.front;
L.front = L.rear;
}
}
void Destorylist(List &L)//销毁队列B方法
{
node *p;
p = L.front;
while (L.front != L.rear)
{
p = L.front->next;
delete L.front;
L.front = p;
}
delete L.front;
}
上图是对应代码的运行结果