我正在尝试创建一个保持算术运算顺序的计算器。我的想法是将中缀表示法转换为后缀表示法,这样我就可以从左到右解决它而不必担心括号。在尝试将中缀转换为后缀表示法之前,我想解决一个后缀表示法练习,我尝试使用节点来解决这个问题,但是我在将数字和运算符划分为节点时遇到了问题。我是指针和结构的新手,所有事情都让我感到困惑。
这是试图划分它的函数:
typedef char* String;
typedef struct node
{
String str;
struct node *next;
} Node;
Node *rpn_divider(String equation, int eq_size)
{
Node *rpn_parts = node_alloc(1); //pointer to first element in the node
Node *part_temp = rpn_parts; //pointer to the lattest element in the node
String temp = malloc(sizeof(char*) * NUM_SIZE);
int i, j; //i = string equation index, j = string temp index
for (i = 0, j = 0; i < eq_size; i++)
{
if (isNum(equation[i]))
temp[j++] = equation[i];
else if (isOper(equation[i]))
{
temp[0] = equation[i];
temp[1] = '\0';
next_node(part_temp, temp);
}
else
{
if (temp == '\0') continue;
temp[j] = '\0';
next_node(part_temp, temp);
j = 0;
}
}
free(part_temp->next);
free(temp);
return rpn_parts;
}
这是 next_node 函数:
void next_node(Node *node, String str)
{
node->str = str;
node->next = node_alloc(1);
node = node->next;
free(str);
str = malloc(sizeof(char*) * NUM_SIZE);
str[0] = '\0';
}
当我尝试打印节点上下文时,它什么也不做:
Node *ptr;
for (ptr = head; ptr != NULL; ptr = ptr->next);
{
printf("The Str = %s", ptr->str);
}