手写队列
队列是一种“先进先出”的线性表,允许在队列一端进行删除运算,在另一端进行插入运算。
1.必要的定义变量
1 #define MAXN 100 2 int queue[MAXN];//开辟队列需要的的数组空间,其中MAXN是队列的最大能入队元素的次数 3 int head = 0 ;//队首指针 4 int tail = 0 ;//队尾指针,如果有新的元素插入,就会插入到这个位置
2.进队
1 //将元素x插入到队列的末尾 2 void push(int x) 3 { 4 if(tail>=MAXN)//判断队列是否溢出 5 cout << "Queue overflow" << endl; 6 else 7 queue[tail++] = x; 8 }
3.弹出队首元素
1 //删除队首元素 2 void pop() 3 { 4 if(head==tail)//判断队列是否为空 5 cout << "Queue is empty" <<endl; 6 else 7 head++; 8 }
4.查询队首元素
1 //查询队首元素 2 int front() 3 { 4 if(head==tail)//判断队列是否为空 5 { 6 cout << "Queue is empty" <<endl; 7 return -1; 8 } 9 else 10 return queue[head]; 11 }
5.查询队尾元素
1 //查询队尾元素 2 int back() 3 { 4 return queue[tail-1]; 5 }
6.查询队列元素个数
1 //查询队列元素个数 2 int size() 3 { 4 return tail-head; 5 }
7.查询队列元素是否为空
1 //查询元素是否为空 2 int empty() 3 { 4 if(head==tail) 5 return 1; 6 else 7 return 0; 8 }
(害怕自己忘了,写下来,方便以后抄)
浙公网安备 33010602011771号