单链表(c语言)

单链表(c语言),第1张

1、单链表的创建
typedef int DataType;
//定义节点
typedef struct LNode {
	struct LNode *next;
	DataType data;
	
}LNode,*LinkList;

结构体后面的LNode为定义节点的指针,而*LinkList是定义表头的指针,所以,创建新节点就用LNode来申请空间节点,而创建表头用LinkList(格式为 LinkList   L,L为一张表的表头),但LNode也可以定义表头,两种方法都行。


 

2.初始化链表的头节点
LNode *starlist(LNode *l)
{
	l = (LNode*)malloc(sizeof(LNode));
	l->next = NULL;
	return l;
}

3.头插法创建链表
void createhead(LNode *L)//L为表头
{
	LNode *p;
	int i = 1;
	int j;
	while (i != 0)
	{
		scanf("%d", &j);
		if (j != -1)
		{
			p = (LNode*)malloc(sizeof(LNode));
			p->data = j;
			p->next = L->next;
			L->next = p;
		}
		else i = 0;
	}
}
4.打印单链表
void print(LNode *L)
{
	LNode *p = L->next;
	printf("该单链表的内容为:");
	while (p!= NULL)
	{
		printf("%d", p->data);
		printf("  ");
		p = p->next;
	}
	printf("\n");
}
5.主函数内容
int main()
{
	LinkList *L=NULL;
	L = starlist(L);
	createhead(L);
	print(L);
    return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/langs/674335.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-19
下一篇 2022-04-19

发表评论

登录后才能评论

评论列表(0条)

保存