这是一个基本的链表,它添加节点然后打印它们,但由于某种原因它无法正常工作。根据我的测试,它在打印列表后失败,直到打印工资时错误地打印了数字,然后终止。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node_s {
char job_title[25];
double hourly_wage;
struct node_s *next;
} node_t;
void print_list(node_t *list);
void add_node(node_t **head, char *title, double hwage);
int main()
{
node_t *list;
list = NULL;
add_node(&list, "Programmer", 32.35);
print_list(list);
add_node(&list, "Analyst", 25.80);
print_list(list);
add_node(&list, "Technician", 17.50);
print_list(list);
add_node(&list, "Clerk", 12.00);
print_list(list);
add_node(&list, "Manager", 53.58);
print_list(list);
return(0);
}
void print_list(node_t *list){
node_t *current;
if (current == NULL) {
printf("\n");
}else{
printf("The job is called:%s\n", current->job_title);
printf("The job pays %d hourly.\n", current->hourly_wage);
print_list(current->next);
}
}
void add_node(node_t **head, char *title, double hwage){
node_t *current = head;
node_t *newNode = (node_t *) malloc(sizeof(node_t));
if (newNode == NULL) {
printf("malloc failed\n");
exit(-1);
}
strcpy(newNode->job_title, title);
newNode->hourly_wage = hwage;
newNode->next = NULL;
while (current->next) {
current = current->next;
}
current->next = newNode;
}
最佳答案
在以下代码部分:
void print_list(node_t *list){
node_t *current;
if (current == NULL) {
您正在将当前指针的未初始化值与 null 进行比较。我想你忘了给它赋值:
current = list;
在 if 指令之前。
关于c - 链接列表无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27069977/