-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlb-34-interleave-half-queue.cpp
More file actions
62 lines (60 loc) · 1.24 KB
/
Copy pathlb-34-interleave-half-queue.cpp
File metadata and controls
62 lines (60 loc) · 1.24 KB
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>
#include <queue>
#include <stack>
#include <vector>
using namespace std;
vector<int> interleave(vector<int> &arr) {
// idea -> 1.push on stack 1st half of queue.
// 2. enqueue back the stack element.
// 3. dequene and enqueue half
// 4. push half in stack
// 5. now interleave
// Create a queue
int n = arr.size();
int i = 0;
queue<int> q;
stack<int> st;
vector<int> ans;
// create a Q
while (i < n) q.push(arr[i++]);
// 1. create stack from half
i = 0;
while (i++ < n / 2) {
st.push(q.front());
q.pop();
}
// 2. enque back
while (st.size()) {
q.push(st.top());
st.pop();
}
// 3. compensation
i = 0;
while (i++ < n / 2) {
q.push(q.front());
q.pop();
}
//
i = 0;
while (i++ < n / 2) {
st.push(q.front());
q.pop();
}
// inderleave
while (st.size()) {
ans.push_back(st.top());
ans.push_back(q.front());
st.pop();
q.pop();
}
return ans;
}
int main() {
vector<int> arr = {1, 2, 3, 4, 5, 6};
vector<int> ans = interleave(arr);
for (auto x : ans) {
cout << x << " ";
}
cout << endl;
return 0;
}