我得到了一个链表,它应该保存结果(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 %3dn",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);
}
您可以通过使用锚节点启动列表来简化代码。锚节点是仅用于其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 %3dn", 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
所有节点。