This article refers to C++ to realize the sequential storage and chained storage of queues . First understand the structural framework, and then use c to implement the content according to the video, and it can also have a higher improvement on c.
Article Directory
Queue is a special data storage structure. The difference from stack is that its data storage and access order is first-in-first-out. The form is as follows: The
implementation code of queue sequential storage and chain storage is attached below:
1. Sequential storage
#include <iostream>
using namespace std;
const int max_size=1024;
//定义队列
class seqqueue
{
public:
void* data[max_size];
int size;
};
//初始化队列
seqqueue* init_seqqueue()
{
seqqueue* queue=new seqqueue;
for (int i = 0; i < max_size; i++)
{
queue->data[i]=NULL;
}
queue->size=0;
return queue;
}
//入队
void push_seqqueue(seqqueue* queue,void* data)
{
queue->data[queue->size]=data;
queue->size++;
}
//返回队头元素
void* front_seqqueue(seqqueue* queue)
{
return queue->data[0];
}
//出队
void pop_seqqueue(seqqueue* queue)
{
for (int i = 0; i < queue->size; i++)
{
queue->data[i]=queue->data[i+1];
}
queue->size--;
}
int main()
{
//创建队列
seqqueue* queue=init_seqqueue();
//创建数据
int arr[9];
for (int i = 0; i < 9; i++)
{
arr[i]=i+1;
}
//数据入队
for (int i = 0; i < 9; i++)
{
cout<<"第"<<i+1<<"个元素入队:"<<arr[i]<<endl;
push_seqqueue(queue,&arr[i]);
}
cout<<endl;
//数据出队
for (int i = 0; i < 9; i++)
{
cout<<"第"<<i+1<<"个元素出队:"<<*((int*)front_seqqueue(queue))<<endl;
pop_seqqueue(queue);
}
system("pause");
return 0;
}
operation result:
2. Chain storage
#include <iostream>
using namespace std;
//创建节点
class node
{
public:
node* next;
};
//创建队列
class linkqueue
{
public:
node head;
int size;
};
//队列初始化
linkqueue* init_linkqueue()
{
linkqueue* queue=new linkqueue;
queue->head.next=NULL;
queue->size=0;
return queue;
}
//入队
void push_linkqueue(linkqueue* queue,node* data)
{
data->next=queue->head.next;
queue->head.next=data;
queue->size++;
}
//出队
void pop_linkqueuq(linkqueue* queue)
{
node* pcurrent=queue->head.next;
for (int i = 0; i < queue->size-1; i++)
{
pcurrent=pcurrent->next;
}
pcurrent=NULL;
queue->size--;
}
//返回队顶元素
node* top_linkqueuq(linkqueue* queue)
{
node* pcurrent=queue->head.next;
for (int i = 0; i < queue->size-1; i++)
{
pcurrent=pcurrent->next;
}
return pcurrent;
}
class my_data
{
public:
node* p;
char data;
};
int main()
{
//创建队
linkqueue* queue=init_linkqueue();
//创建数据
string str="ABCDEFGHI";
my_data data[9];
for (int i = 0; i < str.size(); i++)
{
data[i].p=NULL;
data[i].data=str[i];
}
//入队
for (int i = 0; i < str.size(); i++)
{
cout<<"第"<<i+1<<"个入队元素为:"<<str[i]<<endl;
push_linkqueue(queue,(node*)&data[i]);
}
cout<<endl;
//出队
for (int i = 0; i < str.size(); i++)
{
cout<<"第"<<i+1<<"个出队元素为:"<<((my_data*)top_linkqueuq(queue))->data<<endl;
pop_linkqueuq(queue);
}
system("pause");
return 0;
}
operation result: