我正在尝试创建一个保持算术运算顺序的计算器。我的想法是将中缀符号转换为后缀表示法,以便我可以从左到右解决它而不必担心括号。在尝试将中缀转换为后缀表示法之前,我想解决后缀表示法练习,并尝试使用节点来解决这个问题,但是我遇到了将数字和运算符划分为节点的问题。 我是指针和结构的新手,所有的事情让我感到困惑。
这是试图划分它的函数:
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);
}
答案 0 :(得分:2)
在next_node
函数中,您正在分配内存并将其分配给str的本地副本。这是内存泄漏,调用者永远不会看到str的新值。相反,你可以这样做:
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';
}
并像这样使用它:
next_node(part_temp, &temp);
答案 1 :(得分:2)
你犯了一个大错误。 你在for循环之后放了一个分号,如下所示
for (ptr = head; ptr != NULL; ptr = ptr->next);
应该是这样的
for (ptr = head; ptr != NULL; ptr = ptr->next)
可能会有所帮助。
答案 2 :(得分:1)
String rpn_equation = "2 3 5 + 6 2 + 5 * + *";
,即使是2位数字,或4位数字,但如果我输入3位数字或5位数字,则将其划分错误,我无法理解原因:
Node *rpn_divider(String equation, int eq_size)
{
Node *head = node_alloc(1); //pointer to first element in the node
Node *part_temp = head; //pointer to the lattest element in the node
String temp = malloc(sizeof(char*) * NUM_SIZE);
int i, j = 0; //i = string equation index, j = string temp index
for (i = 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';
part_temp->str = temp;
part_temp->next = node_alloc(1);
part_temp = part_temp->next;
temp = malloc(sizeof(char*) * NUM_SIZE);
temp[0] = '\0';
}
else
{
if (temp[j] == '\0') continue;
temp[j] = '\0';
part_temp->str = temp;
part_temp->next = node_alloc(1);
part_temp = part_temp->next;
temp = malloc(sizeof(char*) * NUM_SIZE);
temp[0] = '\0';
j = 0;
}
}
free(part_temp);
return head;
}
我删除了node_next函数cus它没有用它..