在文章中作者介绍了一种使用c/c++构造通用链表的方法。在c语言中我们编写的每一个链表操作函数都是针对特定的链表类型的。每出现一种新的链表类型就要实现一次链表操作函数,虽然这些操作的逻辑都很相似。在c++中采用泛型编程可以编写针对所有类型的链表操作函数,也就是模板函数。而通用链表比链表模板还有牛逼,在通用链表中链表节点之间的类型可以不同。其实通用链表这个东西早就有了,在linux的内核实现中就构造了一个通用链表。在网上随便一搜就能找到源代码,不过各种宏看的有点烦。在我以上提到的文章中给出了另外一种实现思路,相对比较简单。想要具体了解请看原文。我写了一个小程序测试了一下。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct ListStruct{
struct ListStruct *next;
};
typedef struct ListStruct List,*pList;
struct Node{
char *City;
int Temp;
};
typedef struct Node node,* pNode;
pList Head;
/* function declarations for pListed lists*/
void CreateList(void);
void FreeNode(pList);
void ShowNode(void);
#include "list.h"
#define GETPNODE(p) ((pNode)(p+1))
#define GETCOUNT (*(int *)(Head+1))
void AddToList(void *data,int datasize)
{
pList pn=(pList)malloc(datasize+sizeof(List));
void* p=(void*)(pn+1);
memcpy(p,data,datasize);
pn->next=Head->next;
Head->next=pn;
GETCOUNT++;
}
void CreateList(void)
{
Head=(pList)malloc(sizeof(List)+sizeof(int));
Head->next=NULL;
GETCOUNT=0;
}
void FreeNode(pList n)
{
free(GETPNODE(n)->City);
free(n);
}
void ShowNodes(void)
{
pList pn;
if(GETCOUNT)
{
printf("there are %d nodes\n",GETCOUNT);
for(pn=Head->next;pn;pn=pn->next)
{
printf("%-20s:%3d",GETPNODE(pn)->City,GETPNODE(pn)->Temp);
printf("\n");
}
}
else
printf("Empty List\n");
}
int main(int argc,char*argv[])
{
node n;
int size = sizeof(node);
char buffer[50];
CreateList();
do{
scanf("%s",buffer);
scanf("%d",&n.Temp);
n.City=strdup(buffer);
AddToList(&n,size);
}while(n.Temp!=0);
ShowNodes();
scanf("%s",buffer);
}