zoukankan      html  css  js  c++  java
  • C语言实现链表中结构体嵌套

    1.首先,定义两个结构体,一个用于定义链表,一个用于定义数据

    // 定义数据相关的结构体
    typedef struct Student{
      int stu_id;
      char name[100];
    }Stu;
    
    // 定义链表相关的结构体
    typedef struct Node{
      Stu student;
      struct Node *next;
    }Node,*LinkedList;

    2.链表初始化时需要注意student指向stu_id和name方式,用“.”

    // 链表初始化
    LinkedList LinkedListInit(){
      Node *Head,*L,*LNew;
      int id;
      char name[100];
      // 申请节点空间
      Head = (Node *)malloc(sizeof(Node));
      // 判断是否有足够内存空间
      if(Head == NULL){
        printf("申请空间失败
    ");
        exit(-1);
      }
    
      L = Head;
      L->next = NULL;
    
      for(int i=0;i<2;i++){
        // 分配第一个节点
        LNew = (Node *)malloc(sizeof(Node));
        // 判断是否有足够内存空间
        if(LNew == NULL){
          printf("申请空间失败
    ");
          exit(-1);
        }
        scanf("%d",&id);
        LNew->student.stu_id = id;
        // 注意字符串数组的名字就是首地址,不需要"&"
        scanf("%s",name);
        // 字符复制,用strcpy来复制
        strcpy(LNew->student.name,name);
        L->next = LNew;
        LNew->next = NULL;
        L = LNew;
      }
    
      return Head;
    }

    具体源码demo.c

    #include <stdio.h>
    #include <malloc.h>
    #include <stdlib.h>
    #include <string.h>
    
    typedef struct Student{
      int stu_id;
      char name[100];
    }Stu;
    
    // 定义结构体类型
    typedef struct Node{
      Stu student;
      struct Node *next;
    }Node,*LinkedList;
    
    
    
    // 链表初始化
    LinkedList LinkedListInit(){
      Node *Head,*L,*LNew;
      int id;
      char name[100];
      // 申请节点空间
      Head = (Node *)malloc(sizeof(Node));
      // 判断是否有足够内存空间
      if(Head == NULL){
        printf("申请空间失败
    ");
        exit(-1);
      }
    
      L = Head;
      L->next = NULL;
    
      for(int i=0;i<2;i++){
        // 分配第一个节点
        LNew = (Node *)malloc(sizeof(Node));
        // 判断是否有足够内存空间
        if(LNew == NULL){
          printf("申请空间失败
    ");
          exit(-1);
        }
        scanf("%d",&id);
        LNew->student.stu_id = id;
        scanf("%s",name);
        strcpy(LNew->student.name,name);
        L->next = LNew;
        LNew->next = NULL;
        L = LNew;
      }
    
      return Head;
    }
    
    
    int main(int argc, char const *argv[]) {
      /* code */
      Node *p;
      p = LinkedListInit();
      p = p->next;
      while(p != NULL){
        printf("%d	",p->student.stu_id);
        printf("%s
    ",p->student.name);
    
        p = p->next;
      }
    
      return 0;
    }

  • 相关阅读:
    第七届蓝桥杯JavaA组省赛真题
    第七届蓝桥杯JavaA组省赛真题
    第七届蓝桥杯JavaA组省赛真题
    第七届蓝桥杯JavaA组省赛真题
    Qt自定义model
    Qt Model/View(官方翻译,图文并茂)
    ddd
    java整合spring和hadoop HDFS
    hadoop-2.7.3 在windows环境下安装(无需Cygwin)
    Web Api 自动生成帮助文档
  • 原文地址:https://www.cnblogs.com/xiaomingzaixian/p/9395959.html
Copyright © 2011-2022 走看看