HMHMHT 2023-01-07 15:37 采纳率: 66.7%
浏览 53
已结题

C语言链表首节点(非头结点)未包含实际信息

初学链表,我想请问坛里一些问题。
首先,输出结果链表建立没有问题,但是首结点貌似未赋值在我的代码它更像是头结点。
我想请教一下 如何操作才能让首节点成为实际有信息的第一个节点 而非头结点


int main()
{
    
  Node *head ;
  init_list(&head);
  TCcreate_list(&head);
  print_list(head);
  printf("\n%d",head->value);
  return 0;
    
} 

void init_list(Node **L)
{
     
    (*L) = (Node *) malloc (sizeof(Node));
    (*L)->next = NULL;
    (*L) ->value = 0;
}

void TCcreate_list(Node **phead)
{
   Node *p;
   Node *last;
   int num;
   
   scanf("%d",&num);
   while(num!=-1)
   {    
        p = (Node *)malloc(sizeof(Node));
        p->value =num;
        p->next =NULL;
        
        last = *phead;

        while(last->next)
        {
           last =last->next;
        }
        last ->next = p;
    
        scanf("%d",&num);
       }
    }
    printf("结束循环");
}

我想要达到的结果,如果你需要快速回答,请尝试 “付费悬赏”
  • 写回答

2条回答 默认 最新

  • qzjhjxj 2023-01-07 21:15
    关注

    修改如下,供参考:

    #include <stdio.h>
    #include <stdlib.h>
    typedef struct node{
        int  value;
        struct node* next;
    }Node;
    void init_list(Node** L);
    void TCcreate_list(Node **phead);
    void print_list(Node *head);
    int main()
    {
        
      Node *head;
      init_list(&head);
      TCcreate_list(&head);
      print_list(head);
      printf("\n%d",head->value);
      return 0;
        
    } 
    
    void init_list(Node** L)
    {
        (*L) = NULL;
    }
    
    void TCcreate_list(Node **phead)
    {
       Node *p;
       Node *last;
       int num;
    
       while(1)
       {    
            scanf("%d",&num);
            if (num == -1)   break;
            p = (Node *)malloc(sizeof(Node));
            p->value =num;
            p->next =NULL;
            
            if (!(*phead))
                (*phead) = p;
            else{
                last = (*phead);
                while(last->next)
                    last = last->next;
                last ->next = p;
            }
        }
        printf("结束输入!\n");
    }
    void print_list(Node *head)
    {
        Node *p = head;
        while (p){
            printf("%d ", p->value);
            p = p->next;
        }
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 1月16日
  • 已采纳回答 1月8日
  • 创建了问题 1月7日

悬赏问题

  • ¥15 python点云生成mesh精度不够怎么办
  • ¥15 QT C++ 鼠标键盘通信
  • ¥15 改进Yolov8时添加的注意力模块在task.py里检测不到
  • ¥50 高维数据处理方法求指导
  • ¥100 数字取证课程 关于FAT文件系统的操作
  • ¥15 如何使用js实现打印时每页设置统一的标题
  • ¥15 安装TIA PortalV15.1报错
  • ¥15 能把水桶搬到饮水机的机械设计
  • ¥15 Android Studio中如何把H5逻辑放在Assets 文件夹中以实现将h5代码打包为apk
  • ¥15 使用小程序wx.createWebAudioContext()开发节拍器