电竞比分网-中国电竞赛事及体育赛事平台

分享

數(shù)據(jù)結(jié)構(gòu)項目——循環(huán)隊列與鏈隊列

 流楚丶格念 2022-01-14

循環(huán)隊列

代碼如下:


#include "pch.h"
#include <iostream>
using namespace std;
#define MAXSIZE 5

struct SqQueue
{
char* Base;
int front;
int rear;
};

//初始化循環(huán)隊列
int initqueue(SqQueue &q)
{
q.Base = new char[MAXSIZE];
if (!q.Base)
{
cout << "內(nèi)存空間分配失敗!" << endl;
return 0;
}
q.front = q.rear = 0;
return 1;
}
//求循環(huán)隊列的長度
int getqueuelength(SqQueue q)
{
return (q.rear - q.front + MAXSIZE) % MAXSIZE;
}
//求循環(huán)隊列的頭元素
char getqueuehead(SqQueue q)
{
return q.Base[q.front];//q.front 是下標(biāo)位置
}
//循環(huán)隊列的入隊
int insertqueue(SqQueue &q, char e)
{
if ((q.rear+1)%MAXSIZE==q.front)//這樣隊列就滿了
{
cout << "隊列已滿,無法繼續(xù)插入隊列!" << endl;
return 0;
}
q.Base[q.rear] = e;
q.rear = (q.rear + 1) % MAXSIZE;
cout << "入隊列成功!" << endl;
return 1;
}
//循環(huán)隊列的出隊列
int outputqueue(SqQueue &q, char e)
{
if (q.rear==q.front)
{
cout << "隊列為空,無法出隊列!" << endl;
return 0;
}
e=q.Base[q.front];
q.front = (q.front + 1) % MAXSIZE;
cout << "出隊列成功!" << endl;
return 1;
}
int main()
{
SqQueue q;
initqueue(q);
insertqueue(q, 'a');
insertqueue(q, 'b');
insertqueue(q, 'c');
cout << getqueuehead(q) << endl;;
char c='a';
outputqueue(q,c);
cout << getqueuehead(q) << endl;
outputqueue(q, c);
cout << getqueuehead(q) << endl;
cout << "循環(huán)隊列的長度為:" << getqueuelength(q) << endl;
return 0;
}

結(jié)果為:
在這里插入圖片描述

鏈隊列

代碼如下:

#include "pch.h"
#include <iostream>
using namespace std;

//鏈隊列
typedef struct qnode
{
char data;
qnode *next;
}*queueper;

//頭指針和尾指針
struct linkqueue
{
queueper front;//隊列的尾指針
queueper rear;//隊列的頭指針
};
//初始化隊列
int initlinkqueue(linkqueue &q)
{
//創(chuàng)建新節(jié)點設(shè)置為頭,隊尾隊頭志向該節(jié)點
q.front = q.rear = new qnode;
q.rear->next = NULL;//頭結(jié)點指針域設(shè)置為空
return 0;
}
//獲取隊列的頭元素
char getqueueHead(linkqueue q)
{
if (q.front!=q.rear)
{
return q.front->next->data;
}
}
//鏈隊列入隊列
int insertelem(linkqueue &q,char e)
{
queueper p;
p = new qnode;
p->data = e;
p->next = NULL;
q.rear->next = p;//將新節(jié)點插入到隊列的尾部(后插法)
q.rear = p;//尾指針指向尾結(jié)點
cout << "隊列入隊成功!" << endl;
return 0;
}
//鏈隊列出隊列
int outputqueue(linkqueue &q, char &e)
{
queueper p;
if (q.rear==q.front)
{
cout << "隊列為空,無法出隊列!" << endl;
return 0;
}
p = q.front->next;//指向隊頭元素
e = p->data;//得到隊頭元素的數(shù)據(jù)域
q.front->next = p->next;//修改頭指針
if (q.front==p)
{
q.rear = q.front;
}
delete p;
cout << "出隊列成功!" << endl;
return 1;
}
int main()
{
linkqueue q;
initlinkqueue(q);
insertelem(q, 'a');
insertelem(q, 'b');
insertelem(q, 'c');
insertelem(q, 'd');
cout << "隊列的頭元素為:" << getqueueHead(q) << endl;
char e = 'a';
outputqueue(q, e);
cout << "隊列的頭元素為:" << getqueueHead(q) << endl; 
outputqueue(q, e);
cout << "隊列的頭元素為:" << getqueueHead(q) << endl;
return 0;

結(jié)果為:
在這里插入圖片描述

    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多