因为要补全表达式中左括弧,所以我们可以从表达式末尾开始遍历判断是否需要加括号
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 100
typedef struct { //定义栈的结构
char* base;//栈底
char* top;//栈顶
int stacksize;//栈长
} SqStack;
void Init_Stack(SqStack* s, int stacksize); //初始化栈
void Push(SqStack* s, char e); //在栈顶加入元素
char Pop(SqStack* s);//将栈顶元素出栈
void Init_Stack(SqStack* s, int stacksize) {
s->base = (char*)malloc(stacksize * sizeof(char));
if (!s->base) exit(1);
s->top = s->base;//初始为空栈
s->stacksize = stacksize;
}
void Push(SqStack* s, char e) { //将e插入栈顶
*(s->top) = e;
s->top++;
}
char Pop(SqStack* s) {
(s->top)--;
char e = *(s->top);
return e;//返回删除的元素
}
void handle(char* str) {
int n = strlen(str);//计算字符串长度
int num = 0, ln = 0;
SqStack s;
Init_Stack(&s, MAX);
for (int i = n - 1; i >= 0; i--) {//从字符串末尾开始遍历,可以知道是否需要加‘(’
Push(&s, str[i]);
if (str[i] == ')')//统计‘)’括号的个数
{
num++;
ln = 0;
}
if (str[i] == '+' || str[i] == '-')//统计‘+’‘-’运算符的个数,判断是否需要加括号
ln++;
if (str[i] >= '0' && str[i] <= '9') {
while (str[i - 1] >= '0' && str[i - 1] <= '9') {//需要考虑十位数百位数等多位数
i--;
Push(&s, str[i]);
}
}
while (num > 0) {//假如有多余的’)‘,判断能否在当前位置添加’(‘
if ((str[i] >= '0' && str[i] <= '9' && ln > 0) || i == 0) {
Push(&s, '(');
num--;
ln--;
}
else
break;
}
}
for (int i = 0; s.top > s.base; i++) {
printf("%c", Pop(&s));
}
printf("\n");
}
int main() {
char str[100] = { 0 };
scanf("%s", str);//读取字符串
handle(str);
}
运行结果如下: