关于链表的一个小例子

基础版链表的例子

回顾下链表的创建 和 遍历

/*
14点48分
链表
*/

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>

//定义了一个链表的数据类型
struct Node
{
	int data;
	struct Node* pNext;
};
typedef struct Node node;

//创建一个链表
node* CreateList()
{
	int i, iLen, value;
	node* pHead = NULL;
	pHead = (node*)malloc(sizeof(node));
	if (NULL == pHead)
	{
		printf("链表创建失败\n");
		return NULL;
	}

	node* pTail = pHead;
	pTail->pNext = NULL;

	printf("请输入需要生成的链表节点的个数:len = ");
	scanf("%d", &iLen);

	for (i = 0; i < iLen; ++i)
	{
		printf("请输入第%d个节点的值:", i + 1);
		scanf("%d", &value);

		node* pNode = (node*)malloc(sizeof(node));
		if (pNode == NULL)
		{
			printf("分配失败,程序终止!\n");
			exit(-1);
		}

		
		pNode->data = value;
		pNode->pNext = NULL;
		pTail->pNext = pNode;
		pTail = pNode;		//为下一次进入循环准备
	}

	return pHead;
}

//遍历链表
void traverse_list(node* p)
{
	node* pHead = p->pNext;

	while (pHead != NULL)
	{
		printf("%d\n", pHead->data);
		pHead = pHead->pNext;
	}
}

int main()
{
	struct Node* pHead;		//定义头节点
	pHead = CreateList();
	traverse_list(pHead);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Wuzm_/article/details/104396157