赞
踩
新建一个的头文件stu.h
#ifndef _STU_H
#define _STU_H
typedef struct _stu
{
char sno[5]; //年纪
char name[21]; //姓名
int age; //年龄
int score; //得分
}stu;
#endif
新建一个的头文件.h
#ifndef _LIST_H #define _LIST_H typedef struct _node { void* data; //数据域 struct _node *next; //指针域 }Node; //节点 typedef struct _LIST { Node* head; Node* last; int length; }LIST; //链表 LIST* InitList(); int InsertList(LIST* List, void *data, int size); #endif
新建list.c
#include "stu.h" #include "list.h" #include <stdlib.h> #include <windows.h> #include <string.h> LIST *InitList(){ LIST* List = (LIST*)malloc(sizeof(LIST)); if (List == NULL){ exit(0); } memset(List, 0, sizeof(LIST)); return List; } int InsertList(LIST* List, void *data, int size) { Node* n; if (List == NULL || data == NULL){ return 0; } n = (Node*)malloc(sizeof(Node)); if (n == NULL){ return 0; } n->data = malloc(size); if (n->data == NULL){ free(n); return 0; } memcpy(n->data, data, size); n->next = NULL; if (List->head == NULL){ List->head = n; List->last = n; List->length = 1; } else{ List->last->next = n; List->last = n; List->length++; } return 1; }
新建入口文件main.c
#include "stu.h" #include "list.h" #include <stdio.h> #include <stdlib.h> #include <malloc.h> stu ss[3] = { { "S01", "张三", 22, 100 }, { "S02", "王五", 23, 90 }, { "S03", "小红", 24, 80 } }; int main() { LIST *List = InitList(); Node* node; int i; for (i = 0; i<3; i++) { InsertList(List, &ss[i], sizeof(ss[i])); } node = List->head; while (node!=NULL){ printf("%s\t%s\t\n", ((stu*)(node->data))->sno, ((stu*)(node->data))->name); node = node->next; } system("pause"); return 0; }
输出
S01 张三
S02 王五
S03 小红
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。