初始化单链表

#include <stdio.h>

typedef struct Node
{
	char name[20];
	struct Node *next;
}stud;

/*
 * 初始化一个拥有n个结点的链表
 */
stud *InitList(int n)
{
	//第一个结点(头结点)--->......--->第n个结点--->......--->最后一个结点
	stud *head,*pf,*pb;	//head为头指针, pf为指向两相邻节点的前一节点的指针变量(借助于此指针完成操作), pb为当前节点的指针

	int i;
	for(i=0;i<n;i++)
	{
		pb = (stud *)malloc(sizeof(stud));	//分配新结点
		if(pb == NULL)
		{
			printf("Can't allocate new space!");
			exit(0);
		}

		printf("Please input the name of the %d person:",i+1);
		scanf("%s",pb->name);	//在当前新结点pb的数据域中存储姓名
		pb->next = NULL;	//把当前新结点的链域置为空
		
		if(i == 0)
		{
			head=pf=pb;
		}
		else
		{
			pf->next = pb;	//把新分配的结点地址赋给pf所指向的结点的链域,这样就把上一个节点和当前分配的新结点连在一起了
			pf = pb;	//pf指针向后移动一个结点,和pb指向同一个结点(当前的最后节点),为下一次循环做准备
		}
	}

	return head;	//返回链表头结点的地址
}

int main(int argc, char *argv[])
{
	stud *head;	//保存单链表的表头结点地址的指针
	head = InitList(3);
	printf("%s\n",head->name);
	
	return 0;
}

以下是使用C语言初始化单链表的示例代码: ```c #include <stdio.h> #include <stdlib.h> //定义链表节点的结构体 struct ListNode { int val; struct ListNode *next; }; //初始化链表 struct ListNode* initList(int* nums, int numsSize) { //创建头节点 struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode)); head->val = 0; head->next = NULL; //创建尾节点指针 struct ListNode* tail = head; //遍历数组,创建节点并加入链表 for(int i = 0; i < numsSize; i++) { //创建节点 struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode)); node->val = nums[i]; node->next = NULL; //将节点加入链表 tail->next = node; tail = node; } return head->next; //返回链表的第一个节点 } //打印链表 void printList(struct ListNode* head) { while(head != NULL) { printf("%d ", head->val); head = head->next; } printf("\n"); } int main() { int nums[] = {1, 2, 3, 4, 5}; int numsSize = 5; //初始化链表 struct ListNode* head = initList(nums, numsSize); //打印链表 printList(head); return 0; } ``` 在上面的示例代码中,我们定义了一个名为ListNode的结构体,它包含一个整数值val和一个指向下一个节点的指针next。然后我们定义了两个函数:initList和printList。initList函数用于初始化链表,它接收一个数组和数组大小作为参数,返回链表的第一个节点的指针。printList函数用于打印链表。 在main函数中,我们定义了一个整数数组nums和它的大小numsSize,然后调用initList函数初始化链表,并调用printList函数打印链表。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值