数据结构--有头节点的线性链表基本操作

#include
#include

#define fun_in printf("%s %s %d\n",__FILE__,__FUNCTION__,__LINE__);

//有头节点的链表
typedef struct Link
{
	int data;
	struct Link *pnext;
}link;
//链表初始化
link * LinkInit(int N)
{
	link *p = (link*)malloc(sizeof(link));
	Link *ptemp = p;
	int i;

	for (i = 0; i < N; i++)
	{
		link *a = (link*)malloc(sizeof(link));
		a->data = i;
		a->pnext = NULL;
		ptemp->pnext = a;
		ptemp = ptemp->pnext;
	}
	return p;
}
//显示链表中所有元素
void ShowLink(link *plink)
{
	link *a = plink;
	a = plink->pnext;
	while (a != NULL)
	{
		printf("%d\n", a->data);
		a = a->pnext;
	}
}
//删除链表中某一个数值
link *DealLink(link *plink, int Data)
{
	link *pTemp = plink;

	while (pTemp->pnext != NULL)
	{
		if (pTemp->pnext->data == Data)
		{
			link *del = pTemp->pnext;
			pTemp->pnext = pTemp->pnext->pnext;
			free(del);
			printf("删除成功!\n");
			break;
		}
		pTemp = pTemp->pnext;
	}
	return plink;
}
//链表中在elem后插入一个新节点
link *insertData(link *plink, int elem, int new_data)
{
	link *ptemp = plink->pnext;
	fun_in;
	while (ptemp != NULL)
	{
		if (ptemp->data == elem)
		{
			link *a = (link*)malloc(sizeof(link));
			a->data = new_data;
			a->pnext = ptemp->pnext;
			ptemp->pnext = a;
			break;
		}
		ptemp = ptemp->pnext;
	}	
	return plink;
}

int main()
{
	link *plinkHead;
	plinkHead = LinkInit(10);
	ShowLink(plinkHead);
	insertData(plinkHead, 0, 8);
	ShowLink(plinkHead);
	system("pause");
	return 1;
}

你可能感兴趣的:(算法)