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

  • 相关阅读:
    unix/linux中如何在vi编辑器中方便的跳转到首行和末行?
    如何在Ubuntu中用firefox浏览器查看chm文档?
    sybase数据库技术 :游标可更新与for read only/for update
    PropertyMetadata和UIPropertyMetadata的一点区别
    wpf,离线状态下部分功能不可用。
    C#操作注册服务卸载服务启动服务停止服务.. .
    ContentControl与ContentPresenter区别?
    wpf telerik中的book控件
    C#写入和读出文本文件
    WPF 点击Calendar后,需要点击两次按钮
  • 原文地址:https://www.cnblogs.com/xiaomingzaixian/p/9395959.html
Copyright © 2011-2022 走看看