我试图将中缀表示法表达式转换为后缀表示法(RPN)。这是功能:
String createRPN(String infix)
{
Stack *stack = node_alloc(1); //stack pointer
stack->next = NULL;
String ptr; //index
String RPN = malloc(strlen(infix) + 1);
String start = RPN;
for (ptr = infix; *ptr != '\0'; ptr++)
{
if (isNum(*ptr) || (*ptr == ' ')) *RPN++ = *ptr;
else if (*ptr == '(') push(&stack, '(');
else if (isOper(*ptr))
{
while ((stack != NULL) && (stack->value != '('))
{
if (compareOper(stack->value, *ptr)) *RPN++ = pop(&stack);
else break;
}
push(&stack, *ptr);
}
else if (*ptr == ')')
{
while ((stack != NULL) && (stack->value != '(')) *RPN++ = pop(&stack);
if (stack != NULL) pop(&stack);
}
else;
}
while (stack != NULL) *RPN++ = pop(&stack);
*RPN = '\0';
return start;
}
这是堆栈代码:
typedef struct node
{
int value;
struct node *next;
}Stack;
void push(Stack **node, int value)
{
Stack *temp = node_alloc(1);
if (temp == NULL) return;
temp->value = value;
temp->next = *node;
*node = temp;
}
int pop(Stack **node)
{
if (*node == NULL) return 0;
int num = (*node)->value;
Stack *temp = (*node)->next;
free(*node);
*node = (temp == NULL) ? NULL : temp;
return num;
}
但是在我输入中缀字符串后,例如:
2 * ((3 + 5) + (6 + 2) * 5)
程序崩溃,我需要你的帮助来检测我的错误..