0%

数组模拟队列

队列

一个线性表,在一端放入数据,在另一端弹出数据,先放入的数据先弹出。

与链表的实现方式基本相同

数组模拟的队列的基本操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>

using namespace std;

const int N = 100010;

//将tail设为-1 , 这样在插入了一个数的时候,队头head 就是 tail 队列长度是1
int queue[N], head, tail = -1;

//在队尾插入元素,在队头弹出元素

void push(int x)
{
queue[++tail] = x;
}

string ifempty()
{
if (head > tail)
return "YES";
else
return "NO";
}

void pop()
{
//指针移动,队头的元素相当于被切掉了
head++;
}

int query()
{
return queue[head];
}

int main()
{
int m;
cin >> m;
string op;
while (m--)
{
cin >> op;
if (op == "push")
{
int x;
cin >> x;
push(x);
}
else if (op == "pop")
{
pop();
}
else if (op == "empty")
{
cout << ifempty() << endl;
}
else
cout << query() << endl;
}
return 0;
}