链表节点个数和链表查找

链表节点个数

编写一个返回int类型的函数getLinkNodeNum,在getLinkNodeNum函数里面,定义一个count计数进入循环的次数,也就是指针没有指向NULL之前。

#include <stdio.h>

struct Test
{
	int data;
	struct Test *next;
};

int getLinkNodeNum(struct Test *head)
{
	struct Test *point = head;
	int count = 0;	//初始化为0
	while(point != NULL){
		count++;	//每进一次循环就加1
		point = point->next;	//指针指向下一个首地址
	}
	return count;	
}

int main()
{
	struct Test t1 = {1,NULL};
	struct Test t2 = {2,NULL};
	struct Test t3 = {3,NULL};
	struct Test t4 = {4,NULL};
	struct Test t5 = {5,NULL};
	struct Test t6 = {6,NULL};

	t1.next = &t2;
	t2.next = &t3;
	t3.next = &t4;
	t4.next = &t5;
	t5.next = &t6;

	int ret = getLinkNodeNum(&t1);
	printf("%d\n",ret);	//输出为 6 
	return 0;
}

链表的查找

编写一个查找数据的int类型函数SearchLink,在SearchLink函数里有两个参数,分别是链表的头地址&t1和需要寻找的数据data,在while循环里,指针不指向NULL的话,进入if判断链表里的point->data和需要的data是否一样,一样就返回1,不一样就返回0。在主函数里,定义两个变量,data用来装scanf输入的数据,getNum是承接SearchLink函数返出来的值1或0,接下来进行判断,如果getNum为1,就输出data;如果为0,就输出no!

#include <stdio.h>

struct Test
{
	int data;
	struct Test *next;
};

int SearchLink(struct Test *head, int data)
{
	struct Test *point = head;
	while(point != NULL){
		if(point->data == data){	//与链表里的值做对比
			return 1;
		}
		point = point->next;	//指针指向下一个首地址
	}
	return 0;	
}

int main()
{
	struct Test t1 = {0,NULL};
	struct Test t2 = {2,NULL};
	struct Test t3 = {3,NULL};
	struct Test t4 = {4,NULL};
	struct Test t5 = {5,NULL};
	struct Test t6 = {6,NULL};
	
	t1.next = &t2;
	t2.next = &t3;
	t3.next = &t4;
	t4.next = &t5;
	t5.next = &t6;

	int data,getNum;
	printf("Please input your num\n");
	scanf("%d",&data);
	
	getNum = SearchLink(&t1,data);
	if(getNum == 1){
		printf("%d\n",data);
	}
	if(getNum == 0){
		printf("no!\n");
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值