C++实现1. 使用链表创建栈 2. 完成栈的基本操作,创建、销毁、清空、判断是否为空、获取栈的长度、返回栈顶元素、入栈、出栈 3. 从键盘输入一个四则运算表达式(允许退格操作),完成中序表达式与后序表达式的互相转换并计算结
时间: 2023-06-23 18:10:13 浏览: 174
单链表的插入删除等功能
好的,下面是C++实现:
```
#include <iostream>
#include <cstring>
using namespace std;
struct Node {
char data;
Node *next;
};
class Stack {
private:
Node *top;
int length;
public:
Stack() {
top = NULL;
length = 0;
}
~Stack() {
clear();
}
void clear() {
while (top != NULL) {
Node *temp = top;
top = top->next;
delete temp;
}
length = 0;
}
bool isEmpty() {
return (top == NULL);
}
int getLength() {
return length;
}
char getTop() {
if (isEmpty()) {
return '\0';
}
return top->data;
}
bool push(char data) {
Node *node = new Node;
node->data = data;
node->next = top;
top = node;
length++;
return true;
}
bool pop() {
if (isEmpty()) {
return false;
}
Node *temp = top;
top = top->next;
delete temp;
length--;
return true;
}
};
int priority(char op) {
if (op == '+' || op == '-') {
return 1;
}
if (op == '*' || op == '/') {
return 2;
}
return 0;
}
bool isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}
void infixToPostfix(char infix[], char postfix[]) {
Stack stack;
int len = strlen(infix);
int j = 0;
for (int i = 0; i < len; i++) {
if (infix[i] == '\b') {
if (j > 0) {
j--;
}
continue;
}
if (isdigit(infix[i])) {
postfix[j++] = infix[i];
} else if (isOperator(infix[i])) {
while (!stack.isEmpty() && priority(stack.getTop()) >= priority(infix[i])) {
postfix[j++] = stack.getTop();
stack.pop();
}
stack.push(infix[i]);
} else if (infix[i] == '(') {
stack.push(infix[i]);
} else if (infix[i] == ')') {
while (!stack.isEmpty() && stack.getTop() != '(') {
postfix[j++] = stack.getTop();
stack.pop();
}
if (!stack.isEmpty()) {
stack.pop();
}
}
}
while (!stack.isEmpty()) {
postfix[j++] = stack.getTop();
stack.pop();
}
postfix[j] = '\0';
}
int calculate(char op, int num1, int num2) {
if (op == '+') {
return num1 + num2;
}
if (op == '-') {
return num1 - num2;
}
if (op == '*') {
return num1 * num2;
}
if (op == '/') {
return num1 / num2;
}
return 0;
}
int evaluatePostfix(char postfix[]) {
Stack stack;
int len = strlen(postfix);
for (int i = 0; i < len; i++) {
if (isdigit(postfix[i])) {
stack.push(postfix[i] - '0');
} else if (isOperator(postfix[i])) {
int num2 = stack.getTop();
stack.pop();
int num1 = stack.getTop();
stack.pop();
stack.push(calculate(postfix[i], num1, num2));
}
}
return stack.getTop();
}
int main() {
char infix[100];
char postfix[100];
cout << "请输入一个中序表达式(允许使用退格键):" << endl;
cin.getline(infix, 100);
infixToPostfix(infix, postfix);
cout << "转换后的后序表达式为:" << postfix << endl;
cout << "计算结果为:" << evaluatePostfix(postfix) << endl;
return 0;
}
```
在这个程序中,我们使用了链表来实现栈。栈具有的基本操作都被实现了,并且我们还实现了中序表达式到后序表达式的转换,以及后序表达式的计算。
阅读全文