写一段代码,要求顺序存储实现入栈出栈,把中缀表达式转换为后缀表达式的算法
时间: 2024-05-29 10:08:20 浏览: 100
好的,以下是符合您需求的C++代码:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int precedence(char op) {
if (op == '+' || op == '-') {
return 1;
}
if (op == '*' || op == '/') {
return 2;
}
return 0;
}
string infixToPostfix(string infix) {
stack<char> s;
string postfix = "";
for (int i = 0; i < infix.length(); i++) {
if (infix[i] >= '0' && infix[i] <= '9') {
postfix += infix[i];
}
else if (infix[i] == '(') {
s.push('(');
}
else if (infix[i] == ')') {
while (!s.empty() && s.top() != '(') {
postfix += s.top();
s.pop();
}
if (!s.empty() && s.top() != '(') {
return "Invalid Expression";
}
else {
s.pop();
}
}
else {
while (!s.empty() && precedence(infix[i]) <= precedence(s.top())) {
postfix += s.top();
s.pop();
}
s.push(infix[i]);
}
}
while (!s.empty()) {
postfix += s.top();
s.pop();
}
return postfix;
}
int main() {
string infix = "2+3*4";
cout << "Infix Expression: " << infix << endl;
string postfix = infixToPostfix(infix);
cout << "Postfix Expression: " << postfix << endl;
return 0;
}
对于入栈出栈的实现,您可以使用一个数组来模拟栈,以下是示例代码:
#define MAX_SIZE 1000
class Stack {
private:
int top;
int arr[MAX_SIZE];
public:
Stack() {
top = -1;
}
bool push(int x) {
if (top >= (MAX_SIZE - 1)) {
cout << "Stack Overflow" << endl;
return false;
}
else {
arr[++top] = x;
return true;
}
}
int pop() {
if (top < 0) {
cout << "Stack Underflow" << endl;
return 0;
}
else {
int x = arr[top--];
return x;
}
}
int peek() {
if (top < 0) {
cout << "Stack is Empty" << endl;
return 0;
}
else {
int x = arr[top];
return x;
}
}
bool isEmpty() {
return (top < 0);
}
};
int main() {
Stack s;
s.push(10);
s.push(20);
s.push(30);
cout << s.pop() << endl;
cout << s.peek() << endl;
return 0;
}
希望对您有所帮助!
阅读全文