我有一个链表,它应该保存每场比赛的结果(W 或 L)和获得/失去的分数。到目前为止一切都很好,但是当头部不存在/为空时我遇到了麻烦。我还意识到我对如何实现链表有一个非常糟糕的概述,有人有好的和可以理解的资源吗?不管怎样,这是我的代码:
#include <stdio.h>
#include <stdlib.h>
struct node {
int point;
char outcome;
struct node *next;
};
void add(struct node *data){
if(data == NULL){
data = malloc(sizeof(struct node));
printf("Outcome and points?\n");
int point;
char outcome;
scanf("%c %d",&outcome,&point);
fgetc(stdin);
data->point=point;
data->outcome=outcome;
data->next=NULL;
}else{
struct node *current= data;
while(current->next != NULL){
current = current->next;
}
current->next = malloc(sizeof(struct node));
current=current->next;
printf("Outcome and points?\n");
int point;
char outcome;
scanf("%c %d",&outcome,&point);
fgetc(stdin);
current->point=point;
current->outcome=outcome;
current->next=NULL;
}
}
void print(struct node *data){
struct node *current = data;
while(current != NULL){
printf("%c with %3d\n",current->outcome,current->point);
current = current->next;
}
}
int main()
{
struct node *head=NULL;
add(head);
add(head);
add(head);
print(head);
}
任何帮助将不胜感激:)
最佳答案
当你执行时:
void add(struct node *data){
if(data == NULL){
data = malloc(sizeof(struct node));
head
的值在调用函数中不会改变。
建议改变策略。
struct node* add(struct node *head)
{
if(head == NULL){
head = malloc(sizeof(struct node));
printf("Outcome and points?\n");
int point;
char outcome;
scanf("%c %d",&outcome,&point);
fgetc(stdin);
head->point=point;
head->outcome=outcome;
head->next=NULL;
}else{
struct node *current= head;
while(current->next != NULL){
current = current->next;
}
current->next = malloc(sizeof(struct node));
current=current->next;
printf("Outcome and points?\n");
int point;
char outcome;
scanf("%c %d",&outcome,&point);
fgetc(stdin);
current->point=point;
current->outcome=outcome;
current->next=NULL;
}
return head;
}
然后,改变用法:
int main()
{
struct node *head = add(NULL);
add(head);
add(head);
print(head);
}
关于c - 链表,如果头部不存在如何插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28329374/