Stack & Queue
Stack & Queue
class MyStack {
private:
queue<int> queue1;
queue<int> queue2;
public:
MyStack() {
// Constructor
void push(int x) {
queue2.push(x);
while (!queue1.empty()) {
queue2.push(queue1.front());
queue1.pop();
swap(queue1, queue2);
int pop() {
if (empty()) {
}
int poppedValue = queue1.front();
queue1.pop();
return poppedValue;
int top() {
if (empty()) {
return queue1.front();
bool empty() {
return queue1.empty();
};
int main() {
MyStack s;
s.push(10);
s.push(20);
s.push(30);
cout << s.pop() << " popped from the stack\n"; // Outputs 30
cout << "Top element is: " << s.top() << endl; // Outputs 20
cout << (s.empty() ? "Stack is empty" : "Stack is not empty") << endl; // Outputs "Stack is not
empty"
return 0;
#include <stack>
#include <cctype>
int precedence(char c) {
bool isOperator(char c) {
char c = infix[i];
// If the scanned character is an operand, add it to the postfix output
if (isalnum(c)) {
postfix += c;
else if (c == '(') {
st.push(c);
// If the scanned character is ')', pop and output from the stack
else if (c == ')') {
postfix += st.top();
st.pop();
// If an operator is encountered
else if (isOperator(c)) {
postfix += st.top();
st.pop();
st.push(c);
while (!st.empty()) {
postfix += st.top();
st.pop();
}
return postfix;
int main() {
string infix;
return 0;
#include <bits/stdc++.h>
bool isOperator(char c)
int getPriority(char C)
if (C == '-' || C == '+')
return 1;
return 2;
else if (C == '^')
return 3;
return 0;
int l = infix.size();
stack<char> char_stack;
string output;
if (isalpha(infix[i]) || isdigit(infix[i]))
output += infix[i];
char_stack.push('(');
output += char_stack.top();
char_stack.pop();
char_stack.pop();
// Operator found
else {
if (isOperator(char_stack.top())) {
if (infix[i] == '^') {
while (
getPriority(infix[i])
<= getPriority(char_stack.top())) {
output += char_stack.top();
char_stack.pop();
else {
while (
getPriority(infix[i])
< getPriority(char_stack.top())) {
output += char_stack.top();
char_stack.pop();
}
// Push current Operator on stack
char_stack.push(infix[i]);
while (!char_stack.empty()) {
output += char_stack.top();
char_stack.pop();
return output;
// Get Postfix
// Reverse Postfix
int l = infix.size();
// Reverse infix
reverse(infix.begin(), infix.end());
if (infix[i] == '(') {
infix[i] = ')';
infix[i] = '(';
}
// Reverse postfix
reverse(prefix.begin(), prefix.end());
return prefix;
// Driver code
int main()
string s = ("x+y*z/w+u");
// Function call
return 0;