-
Notifications
You must be signed in to change notification settings - Fork 1
/
5c) Queue sort using stack.cpp
59 lines (47 loc) · 1.05 KB
/
5c) Queue sort using stack.cpp
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
// Check if we can sort a Queue using a stack or not
#include<iostream>
#include<queue>
#include<stack>
using namespace std;
bool checkSorted(queue<int> qu , int n){
stack<int>st;
int expected = 1;
while(!qu.empty()){
int front_ele = qu.front();
qu.pop();
if(front_ele == expected){
expected++;
}
else{
if(!st.empty() && front_ele > st.top()){
return false;
}
else{
st.push(front_ele);
}
}
while(!st.empty() && st.top() == expected){
st.pop();
expected++;
}
}
// if the final expected element value is equal
// to initial Queue size and the stack is empty.
return (expected - 1 == n && st.empty());
}
int main(){
queue<int> q;
q.push(5);
q.push(1);
q.push(2);
q.push(3);
q.push(4);
int n = q.size();
if(checkSorted(q,n)){
cout << "YES\n";
}
else{
cout << "NO\n";
}
return 0;
}