通用链表

文章中作者介绍了一种使用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);
}	


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值