当前位置:   article > 正文

C语言实现单向链表_#ifndef list

#ifndef list

新建一个的头文件stu.h

#ifndef _STU_H
#define _STU_H
typedef struct _stu
{
	char sno[5];   //年纪
	char name[21]; //姓名
	int age;       //年龄
	int  score;    //得分
}stu;
#endif
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

新建一个的头文件.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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

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



  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

新建入口文件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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36

输出

S01     张三
S02     王五
S03     小红
  • 1
  • 2
  • 3
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/859755
推荐阅读
相关标签
  

闽ICP备14008679号