单链表的基本操作(三)单链表的创建

1、尾插法创建一个单链表(顺序输入一个数组)

Linklist Createndlist(int a[N])
{
	Linklist L;
	L = (Lnode*)malloc(sizeof(Lnode));
	if (L == NULL)
	{
		cout << "error";
		exit(0);
	}
	else L->next = NULL;
	Linklist tail, p;
	tail = L;
	int j;
	for (j = 0; j < N; j++)
	{
		p = (Lnode*)malloc(sizeof(Lnode));
		if (p == NULL)
		{
			cout << "error";
			exit(0);
		}
		else p->next = NULL;
		p->data = a[j];
		tail->next = p;
		tail = p;
	}
	tail->next = NULL;
	return L;
}

2、头插法创建一个单链表(逆序输入一个数组)

Linklist Greatheadlist(int a[N])
{
	int j;
	Linklist L;
	L = (Lnode*)malloc(sizeof(Lnode));
	if (L == NULL)
	{
		cout << "error";
		exit(0);
	}
	else L->next = NULL;
	for (j = 0; j < N; j++)
	{
		Linklist p;
		p = (Lnode*)malloc(sizeof(Lnode));
		if (p == NULL)
		{
			cout << "error";
			exit(0);
		}
		else p->next = NULL;
		p->data = a[j];
		p->next = L->next;
		L->next = p;
	}
	return L;
}
上一篇:单链表的创建


下一篇:7.3