#include<iostream>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
using namespace std;
typedef struct LinkQueueNode{
char data;
LinkQueueNode *next;
}LinkQueueNode;
typedef struct LinkQueue{
LinkQueueNode *front;
LinkQueueNode *rear;
int length;
int lengthOfCurrent;
}LinkQueue;
LinkQueue *Q=(LinkQueue*)malloc(sizeof(LinkQueue));
//初始化队列操作,定义队列长度
int InitialQueue(LinkQueue *Q)
{
Q->front=(LinkQueueNode*)malloc(sizeof(LinkQueueNode));
if(Q->front!=NULL){
Q->front->next=NULL;
Q->rear=Q->front;
cout<<"输入队列长度\n";
cin>>Q->length;
Q->lengthOfCurrent=0;
return TRUE;
}
else
return FALSE;
}
//将元素入队操作
int EnterQueue(LinkQueue *Q,char data)
{
if(Q->length==Q->lengthOfCurrent){
cout<<"列表已经满了\n";
cout<<"按#键则输入结束\n";
return FALSE;
}
LinkQueueNode *newNode=(LinkQueueNode*)malloc(sizeof(LinkQueueNode));
if(newNode==NULL)
return FALSE;
newNode->data=data;
Q->rear->next=newNode;
Q->rear=newNode;
Q->rear->next=NULL;
Q->lengthOfCurrent++;
return TRUE;
}
//将队首元素进行出队列
int QuitQueue(LinkQueue *Q)
{
LinkQueueNode *p=(LinkQueueNode*)malloc(sizeof(LinkQueueNode));
if(Q->front==Q->rear){
cout<<"队列中无元素!\n";
return FALSE;
}
p=Q->front->next;
Q->front->next=p->next;
free(p);Q->lengthOfCurrent--;
return TRUE;
}
//得到队首元素
char GetQueueHead(LinkQueue *Q)
{
if(Q->front==Q->rear)
return FALSE;
else{
return Q->front->next->data;
}
}
int FindIndexOfNode(LinkQueue *Q,char data)
{
LinkQueueNode *p=Q->front->next;
if(p->next==NULL){
cout<<" 队列已经为空\n";
return FALSE;
}int current=1;
while(p!=NULL)
{
if(p->data==data)
return current;
else
p=p->next;
current++;
}
return FALSE;
}
//对队列添加元素(元素个数限制为定义的队列长度)
void procInitial()
{
char data;
InitialQueue(Q);
cin>>data;
while(data!='#')
{
EnterQueue(Q,data);
cin>>data;
}
}
//输出队列中各元素
void procOutput()
{
LinkQueueNode *p=(LinkQueueNode*)malloc(sizeof(LinkQueueNode));
p=Q->front->next;
while(p!=NULL)
{
cout<<p->data<<"\n";
p=p->next;
}
cout<<"当前队列长度为"<<Q->lengthOfCurrent<<"\n\n";
}
int main()
{
char data;
procInitial();
cout<<"输入要查找的元素(0为没有找到,其他正整数为找到元素在队列中的位置)\n";
cin>>data;
int flag=FindIndexOfNode(Q,data);
cout<<"您要查找的元素位置为"<<flag<<"\n";
cout<<"出队列两次\n";
QuitQueue(Q);QuitQueue(Q);
procOutput();
cout<<"获取队首元素"<<GetQueueHead(Q)<<"\n";
return 0;
}
链队列插入,删除,查找操作的实现
最新推荐文章于 2022-01-01 13:58:12 发布
本文介绍了一种基于链表实现的链式队列数据结构,并提供了详细的C++代码实现。包括队列的初始化、元素入队与出队、获取队首元素等功能。此外,还实现了查找指定元素在队列中的位置。
816

被折叠的 条评论
为什么被折叠?



