Queue

Queue 可以array 、 linked list實現

algorithm Average Worst case
space O(n) O(n)
search O(n) O(n)
insert O(1) O(1)
delete O(1) O(1)
  • 常用方法 push pop front back size empty swap emplace
  • back() front() push_back() pop_front()

    priority_queue 用vector 實作 但資料結構是 max-heap

  • 常用方法 push pop top size empty swap emplace
  • front() push_back() pop_back()
  • heap 插入刪除元素時間 O(logn)

deque

  • 存取方法 deq.at(i)/deq[i] front back
  • 容量 size empty resize max_size shrink_to_fit
  • 修改器 push_back/emplace_back pop_back push_front/emplace_front pop_front insert/emplace clear erase swap
  • 疊代 begin end rbegin rend cbegin cend crbegin crend

implement code

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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <iostream>
#include <stack>
using namespace std;

class QueueStack
{
private:
stack<int> sta;

public:
QueueStack() {}

int front();
int back();
int size();
bool empty();
void pop();
void push(int x);
};

int QueueStack::front()
{
stack<int> tmp;
while (!sta.empty())
{
tmp.push(sta.top());
sta.pop();
}
int ret = tmp.top();
while (!tmp.empty())
{
sta.push(tmp.top());
tmp.pop();
}
return ret;
}

int QueueStack::back()
{
if (sta.empty())
{
std::cout << "The queue is empty" << endl;
return -1;
}
return sta.top();
}

int QueueStack::size()
{
return sta.size();
}

bool QueueStack::empty()
{
return sta.empty();
}

void QueueStack::pop()
{
if (sta.empty())
{
std::cout << "The queue is empty" << endl;
return;
}

stack<int> tmp;
while (!sta.empty())
{
tmp.push(sta.top());
sta.pop();
}
int ret = tmp.top();
tmp.pop();
while (!tmp.empty())
{
sta.push(tmp.top());
tmp.pop();
}
// return ret;
}

void QueueStack::push(int x){
sta.push(x);
}

void print(QueueStack q){
stack<int> tmp;
while (!q.empty())
{
cout<<q.front()<<" ";
tmp.push(q.front());
q.pop();
}
cout<<endl;
}
int main(){
QueueStack q;
q.pop();
q.push(1);
q.push(2);
q.push(3);
q.push(4);
q.push(5);
q.push(6);
q.pop();
print(q);
}