c - 链表,如果头部不存在如何插入?

标签 c struct linked-list head

我有一个链表,它应该保存每场比赛的结果(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/

相关文章:

c - 这种C结构体定义有什么好处呢?

c++ - 删除结构的指针是否也会删除结构内的指针?

c++ - 为什么我不能在此链接列表中打印第一个元素?

java - 读取文件时,我尝试将每一行存储到相关的LinkedList中,但是无法读取第一个字符。这怎么样?

c - 在 C 中,有哪些方法可以使函数在其调用之间共享数据?

c - *++*p 是可接受的语法吗?

将负数转换为正数但保持正数不变

解析(选项)参数的正确方法,有关 getopt(3) 和 argv 的问题

c++ - 按姓氏然后名字对结构进行排序

c++ - 在二叉搜索树中插入值