队列及其相关操作
程序员文章站
2022-07-14 14:28:28
...
队列的简要提点
- 队列(queue)是一种先进先出(FIFO, first in first out)的表。有队首和队尾,队尾进(插入)元素,队首出(删除)元素。
- 队列的基本操作主要有:入队(Enqueue)、出队(Dequeue)。
- 队列的实现方式也有两种:基于链表和基于数组。
队列的数组实现
- 基本的数据结构:存放元素的数组elemList,表示队首位置的front,表示队尾位置的rear,表示当前队列长度的length
代码实现(C/C++)
#include<iostream>
using namespace std;
typedef int ElemType;
const int MAXSIZE = 10;
typedef struct {
int front; // 队首
int rear; // 队尾
int length; // 队长度
ElemType elemList[MAXSIZE];
}Deque;
void initDeque(Deque *De) // 初始化队列
{
De->front = 0;
De->rear = -1;
De->length=0;
}
int isEmpty(Deque *De) // 判断队列是否为空
{
return De->length==0;
}
int isFull(Deque *De)
{
return De->length == MAXSIZE;
}
void Enqueue(Deque *De, ElemType x) // 入队列
{
if (isFull(De))
{
cout << "Have been Filled!\n";
exit(1);
}
else
{
De->elemList[++De->rear] = x;
De->length++;
}
}
ElemType Dequeue(Deque *De) // 出队列
{
if (isEmpty(De))
{
cout << "Empty!\n";
exit(1);
}
De->length--;
return De->elemList[De->front++];
}
ElemType Front(Deque *De) // 取队首元素
{
return De->elemList[De->front];
}
ElemType Rear(Deque *De) // 取队尾元素
{
return De->elemList[De->rear];
}
void print(Deque *De) // 打印队列
{
cout << "Now the Deque contents: " << endl;
for (int i = De->front;i <= De->rear;i++)
{
cout << De->elemList[i] << " ";
}
cout << endl;
}
int main()
{
const ElemType date[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Deque* myDeque = new Deque; // 初始化队列
initDeque(myDeque);
if (isEmpty(myDeque))
cout << "Empty Deque, now enqueue some values... " << endl;
for (int i = 0;i < 9;i++)
{
Enqueue(myDeque, date[i]);
}
print(myDeque);
cout << "Enqueue a number to the Deque: \n";
ElemType number;
cin >> number;
Enqueue(myDeque, number);
print(myDeque);
cout << "Dequeue twice from the Deque...\n";
Dequeue(myDeque);
Dequeue(myDeque);
print(myDeque);
cout << "The Front value of the Deque now is: " << Front(myDeque) << endl;
cout << "The Rear value of the Deque now is: " << Rear(myDeque) << endl;
system("pause");
return 0;
}
操作运行结果
Empty Deque, now enqueue some values...
Now the Deque contents:
1 2 3 4 5 6 7 8 9
Enqueue a number to the Deque:
15
Now the Deque contents:
1 2 3 4 5 6 7 8 9 15
Dequeue twice from the Deque...
Now the Deque contents:
3 4 5 6 7 8 9 15
The Front value of the Deque now is: 3
The Rear value of the Deque now is: 15
上一篇: 质数的多种实现方法
下一篇: 手写实现apply,call,bind