C语言实现单向链表

新建一个的头文件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     小红
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

reg183

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值