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;
    }

  • 相关阅读:
    Linux IO接口 监控 (iostat)
    linux 防火墙 命令
    _CommandPtr 添加参数 0xC0000005: Access violation writing location 0xcccccccc 错误
    Visual Studio自动关闭
    Linux vsftpd 安装 配置
    linux 挂载外部存储设备 (mount)
    myeclipse 9.0 激活 for win7 redhat mac 亲测
    英文操作系统 Myeclipse Console 乱码问题
    Linux 基本操作命令
    linux 查看系统相关 命令
  • 原文地址:https://www.cnblogs.com/xiaomingzaixian/p/9395959.html
Copyright © 2011-2022 走看看