链表节点个数
编写一个返回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;
}