计算链表节点个数
int totalNodeNum(struct Test* phead)
{
int cnt=0;
while(phead!=NULL)
{
cnt++;
phead=phead->next;
}
return cnt;
}
链表的查找
int searchNode(struct Test* phead,int data)
{
while(phead!=NULL)
{
if(phead->data==data)
{
return 1;
}
phead=phead->next;
}
return 0;
}
示例
计算链表中节点的个数,查找链表中是否有数字 “8” 和 “9”。
#include <stdio.h>
struct Test
{
int data;
struct Test* next;
};
void printLink(struct Test* phead)
{
struct Test* point=phead;
while(point!=NULL)
{
printf("%d ",point->data);
point=point->next;
}
putchar('\n');
/*
while(1)
{
if(phead!=NULL)
{
printf("%d ",phead->data);
phead=phead->next;
}
else
{
putchar('\n');
break;
}
}
*/
}
int totalNodeNum(struct Test* phead)
{
int cnt=0;
while(phead!=NULL)
{
cnt++;
phead=phead->next;
}
return cnt;
}
int searchNode(struct Test* phead,int data)
{
while(phead!=NULL)
{
if(phead->data==data)
{
return 1;
}
phead=phead->next;
}
return 0;
}
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};
struct Test t7={7,NULL};
struct Test t8={8,NULL};
t1.next=&t2;
t2.next=&t3;
t3.next=&t4;
t4.next=&t5;
t5.next=&t6;
t6.next=&t7;
t7.next=&t8;
printLink(&t1);
int total=0;
total=totalNodeNum(&t1);
printf("total num=%d\n",total);
int judge=searchNode(&t1,8);
if(judge==1)
{
printf("8:have\n");
}
if(judge==0)
{
printf("8:No\n");
}
judge=searchNode(&t1,9);
if(judge==1)
{
printf("9:have\n");
}
if(judge==0)
{
printf("9:No\n");
}
return 0;
}
运行结果