1、准备知识
1.1 写通用的 链表函数库
typedef int INT32;
//main.cpp
#include
#include
#include
struct Student
{
int number;
char *name;
};
void print_student(void *data)
{
struct Student *p=(struct Student *)data;
printf("number is %d\tname is %s\n",p->number,p->name);
return;
}
int main()
{
struct Student stu[3]={1001,"zhangsan",1002,"lisi",1003,"wangwu"};
struct Node *head=link_create();
link_add(&head,(void *)&stu[0]);
link_add(&head,(void *)&stu[1]);
link_add(&head,(void *)&stu[2]);
link_foreach(head,print_student);
return 0;
}
//list.h
struct Node;
typedef void (*pfun)(void *data); //将函数原型中的 函数 括起来,再加*-->函数指针变量;前面加typedef则变量-->类型
struct Node * link_create();
void link_add(struct Node **head,void *data);
void link_foreach(struct Node *head, pfun print_student); //pfun函数指针类型
//list.cpp
#include
#include
#include
#include "list.h"
struct Node
{
void *data;
struct Node *next;
};
struct Node * link_create()
{
struct Node * head=NULL;
return head;
}
void link_add(struct Node **head,void *data)
{
struct Node *p=(struct Node *)malloc(sizeof(struct Node));
struct Node *p2;
p->data=data;
p->next=NULL;
if(*head==NULL)
{
*head=p;
}
else
{
p2=*head;
while(p2->next!=NULL)
{
p2=p2->next;
}
p2->next=p;
}
return;
}
void link_foreach(struct Node *head, pfun print_student)
{
struct Node *p=head;
if(head==NULL)
{
return;
}
else
{
while(p!=NULL)
{
//printf("%d %s\n",p->number,p->name);
print_student(p->data);
p=p->next;
}
}
return;
}