查找链表节点数量
#include <stdio.h>
struct Test
{
int data;
struct Test *next;
};
// 遍历链表
void printLink(struct Test *head)
{
struct Test *p = head;
while(p != NULL){
printf("%d ",p->data);
p = p->next;
}
}
// 获取链表节点数量
int getLinkTotalNodeNum(struct Test *head)
{
int cnt = 0;
struct Test *p = head;
while(p != NULL){
cnt++;
p = p->next;
}
return cnt;
}
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};
t1.next = &t2;
t2.next = &t3;
t3.next = &t4;
t4.next = &t5;
printf("use t1 to print three nums3\n");
printLink(&t1);
putchar('\n');
int ret = getLinkTotalNodeNum(&t1);
printf("totalNode=%d\n", ret);
return 0;
}
查找节点是否存在
int searchLink(struct Test *head, int data)
{
struct Test *p = head;
while(p != NULL){
if(p->data == data){
return 1;
}
p = p->next;
}
return 0;
}
ret = searchLink(&t1, 1);
if(ret == 1){
printf("yes\n");
}else{
printf("no\n");
}