0
这是一个基本链接列表,它添加节点然后打印它们,但由于某些原因它无法正常工作。从我测试过的东西打印出列表后,它会失败,直到打印工资的地方打印不正确的数字,然后终止。链接列表无法正常工作
#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;
}
'node_t * current = head;'头部类型为'node_t **'。 – 2014-11-21 20:42:28
您的打印方法无法初始化“当前”;它拥有垃圾,因此行为未定义。 – 2014-11-21 20:46:28
@Ieaturaw不要忘记标记我的答案是最好的,因为我相信你会使用我展示的代码。 – 2014-11-21 21:10:56