我有一个链接列表,应该保存每个匹配的结果(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);
}
任何帮助将不胜感激:)
答案 0 :(得分:2)
执行时:
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);
}
答案 1 :(得分:0)
您可以通过使用锚节点启动列表来简化代码。锚节点是仅用于其next
指针的节点。在下面的代码中,对calloc
的调用会创建锚节点,并将锚中的所有字段都设置为0
。换句话说,使用next == NULL
创建节点。
请注意,在打印列表时,for
循环首先跳过锚点节点for (list = list->next;...)
#include <stdio.h>
#include <stdlib.h>
struct node
{
int point;
char outcome;
struct node *next;
};
void add( struct node *list )
{
struct node *data;
data = malloc(sizeof(struct node));
data->next = NULL;
printf("Outcome and points?\n");
scanf("%c %d",&data->outcome,&data->point);
fgetc(stdin);
while (list->next != NULL)
list = list->next;
list->next = data;
}
void print( struct node *list )
{
for (list = list->next; list != NULL; list = list->next)
printf("%c with %3d\n", list->outcome, list->point);
}
int main()
{
struct node *head = calloc( 1, sizeof(struct node) );
add(head);
add(head);
add(head);
print(head);
}
附注:我已经省略了一些错误检查以保持简单,您应该真正检查来自calloc
,malloc
和scanf
的返回值并处理任何错误。当然,您应该free
最后的所有节点。