这段代码中存在一些问题导致输出结果始终相同。以下是需要修正的地方:
在
InitNode函数中,应该将传入的指针head指向新分配的头结点H,而不是将新分配的头结点赋值给H。在
creat函数中,应该使用传入的头结点指针进行链表操作,而不是在函数内部重新分配一个头结点。在
output函数中,在调用printf输出时,应该使用%f^%d而不是&p->X, &p->Z。
此外,你还需要在主函数中通过传递指针来修改链表并打印输出结果。修复后的代码如下所示:
#include <stdio.h>
#include <malloc.h>
typedef struct node {
float X;
int Z;
struct node* next;
} Node;
bool InitNode(Node** head) {
*head = (Node*)malloc(sizeof(Node));
if (*head == NULL) return false;
(*head)->next = NULL;
return true;
}
void creat(Node* head) {
Node* r = head, * s; //r为表尾指针
int a = 1, b = 1;
while (1) {
s = (Node*)malloc(sizeof(Node));
scanf("%d,%d", &a, &b);
if (a == 0 && b == 0) break;
else {
s->X = (float)a;
s->Z = b;
r->next = s;
r = s;
}
}
}
void output(Node* head) {
Node* p = head->next;
while (p != NULL) {
printf("%.1f^%d ", p->X, p->Z);
p = p->next;
}
printf("\n");
}
int main() {
Node* head;
if (!InitNode(&head)) {
printf("Initialization failed.\n");
return 0;
}
creat(head);
output(head);
return 0;
}
修正后的代码将能够正确读取输入数据,并按照指数表达式的格式打印输出链表节点。
内容由零声教学AI助手提供,问题来源于学员提问




