Lab02 Stacks
Lab02 Stacks
#include <iostream>
// Function to check if the stack is empty
// Define a Node structure for the stack bool isEmpty() {
template <typename T> return top == nullptr;
struct Node { }
T data;
Node* next; // Function to get the top element of the stack without
}; popping it
T peek() {
// Define the Stack class using templates if (isEmpty()) {
template <typename T> throw std::out_of_range("Stack is empty");
class Stack { }
private: return top->data;
Node<T>* top; }
2. Given an expression string exp, write a program to examine whether the pairs and the orders of “{“, “}”,
“(“, “)”, “[“, “]” are correct in the given expression.
while(!st.isEmpty() ){
//Rút lần lượt từng phần tử của stack
n = st.pop();
//chuyển sang dạng ký tự và in kết quả
std::cout<<digitChar[n];
}
}
4. Implement a C/C++ code to convert an infix expression to postfix, for example, input an infix
expression (20+5)/5+(7-3)*100 20 5 + 5 / 7 3 - 100 * +
Algorithm:
1. Scan the infix expression from left to right.
2. If the scanned character is an operand, output to postfix.
3. Else,
1. If the precedence of the scanned operator is greater than the precedence of the operator in the
stack [or the stack is empty, or stack contain ‘)’], push it to stack.
2. Else, pop the operator to postfix from the stack until the precedence of the scanned operator is
less-equal to the precedence of the operator residing on the top of the stack. Push the scanned
operator to the stack.
4. If the scanned character is an ‘(‘, push it to the stack.
5. If the scanned character is an ‘)’, pop and output from the stack until an ‘(‘ is encountered.
6. Repeat steps 2-6 until infix expression is scanned.
7. Pop and output until the stack is empty.
// Function to return precedence of operators
int priority(char c){
if (c == '^')
return 3;
else if (c == '/' || c == '*')
return 2;
else if (c == '+' || c == '-')
return 1;
else
return -1;
}
Stack<char> st;
string postfix;
// If an operator is scanned
else {
while (!st.isEmpty()
&& priority(infix[i]) <= priority(st.peek())) {
postfix = postfix + st.pop() + " ";
}
st.push(c);
}
}