在链表中计算链表元素的个数并查找链表元素

1.在链表中查找链表的元素,如果存在该元素,打印有,否则打印没有。

#include <stdio.h>


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

void  printlink(struct Test *head)
{  
	   struct  Test  *point;//定义结构体指针

	  point=head;//让结构体指针等于链表的头

      while(1)
      {
            if(point != NULL)
	    {
	         printf("%d ",point->data);
	         //如果指针不为空,打印链表中的元素
             point=point->next;
           //因为要打印链表中的元素指针要往后偏移,
	    }

	    else
	    {
		      putchar('\n');
	          break;
	    }

      }   
}


 int   searchLink(struct Test *head,int data)
{
      
       while(head != NULL)
      {
      
         if(head->data==data)
         //如果在链表中找到元素,返回1,在mian函数的
         //被调函数中,打印信息。
        {
             return  1;
	    }
	     head=head->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};

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

       printlink(&t1);
       int  ret;
       
       ret=searchLink(&t1,1);
       //从链表中的t1的位置寻找1
       if(ret==0)
       {
              printf("no 1\n");
       }

       else
	  {
	     printf("have 1\n");
	  }
    
       ret=searchLink(&t1,8);
       //从链表中的t1的位置寻找8
       if(ret==0)
       {
              printf("no 8\n");
       }

       else
	{
	     printf("have 8\n");
	}
       return  0;
}

运行结果:
在这里插入图片描述

——@上官可编程

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值