队列学习

//1.STL中的队列
#include <iostream>
#include <queue>
#include <string>
using namespace std;
struct student{
int english,math;
student(){english=0;math=0;}
student(int english,int math){
this->english=english;
this->math=math;
}
};
int main(){
queue<int> q;//元素是int
cout<<q.empty()<<endl;//1
q.push(111);
q.push(222);
q.push(333);
cout<<"队尾元素:"<<q.back()<<endl;
cout<<"元素个数:"<<q.size()<<endl;
while(!q.empty()){
cout<<q.front()<<"\t";//读队首元素,不删除
q.pop();//出队
}
cout<<endl;


queue<student> q2;
q2.push(student(88,77));
q2.front();
student s=q2.front();
cout<<s.english<<","<<s.math<<endl;


return 0;
}


//2.实现队列
#include <iostream>
using namespace std;


typedef struct QNode* PtrToNode;
typedef char* ElementType;
typedef int Position;


struct QNode{
ElementType* Data;//指向字符串数组
Position Front,Rear;
int MaxSize;
};


typedef PtrToNode Queue;
//1.建队
Queue CreateQueue(int MaxSize){
Queue Q=(Queue)malloc(sizeof(struct QNode));//分配空间
Q->Data=(ElementType*)malloc(MaxSize*sizeof(ElementType));
Q->Front=0;
Q->Rear=0;
Q->MaxSize=MaxSize;
return Q;
}
//2.判满
bool IsFull(Queue Q){
return (Q->Rear+1)%Q->MaxSize==Q->Front;
}
//3.入队
bool AddQ(Queue Q,ElementType X){
if(IsFull(Q)){
cout<<"队列满!"<<endl;
return false;
}else{
Q->Rear=(Q->Rear+1)%Q->MaxSize;
Q->Data[Q->Rear]=X;
return true;
}
}
//4.留下一些待实现
int main(){
Queue Q=CreateQueue(4);
cout<<IsFull(Q)<<endl;//0
AddQ(Q,"兰小草");
AddQ(Q,"焦裕禄");
AddQ(Q,"孔繁森");
AddQ(Q,"雷锋");
cout<<IsFull(Q)<<endl;//1
return 0;
}

猜你喜欢

转载自blog.csdn.net/Yuoliku/article/details/79876045