0
我試圖將中綴表示法轉換爲後綴notatin(RPN)。 這裏是功能:從中綴創建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)
程序崩潰,我需要你幫助檢測我的錯誤..
THX是沒有意義的,但它仍然不工作,併爲字符串的大小(中綴表達式已經比後綴大,因爲它有「()」和後綴不包括他們)..但真正的問題,我注意到它我沒有從createRPN返回字符串,所以我改變了它,但程序仍然崩潰.. – PieThon