当前位置:   article > 正文

数据结构例题

数据结构例题

区分函数中引用变量和指针的用法

1.定义整型a,b,分别输入他们的值,再交换之后输出。

输入:1 2          输出:a=2,b=1

错误1:输出为a=1,b=2,只是形参值改变

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. void swap(int p,int q)
  4. {
  5. int t;
  6. t=p;
  7. p=q;
  8. q=t;
  9. }
  10. int main()
  11. {
  12. int a,b;
  13. scanf("%d%d",&a,&b);
  14. swap(a,b);
  15. printf("a=%d,b=%d",a,b);
  16. return 0;
  17. }

 错误2:输出为a=1,b=2,只是地址交换了,实参未改变

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. void swap(int *p,int *q)
  4. {
  5. int *t;
  6. t=p;
  7. p=q;
  8. q=t;
  9. }
  10. int main()
  11. {
  12. int a,b;
  13. scanf("%d%d",&a,&b);
  14. swap(a,b);
  15. printf("a=%d,b=%d\n",a,b);
  16. return 0;
  17. }

 错误3:输出为a=2,b=2

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. void swap(int *p,int *q)
  4. {
  5. int *t;
  6. t=p;
  7. *p=*q;
  8. q=t;
  9. }
  10. int main()
  11. {
  12. int a,b;
  13. scanf("%d%d",&a,&b);
  14. swap(a,b);
  15. printf("a=%d,b=%d\n",a,b);
  16. return 0;
  17. }

 正确1:直接对指针所指的值进行修改

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. void swap(int *p,int *q)
  4. {
  5. int t;
  6. t=*p;
  7. *p=*q;
  8. *q=t;
  9. }
  10. int main()
  11. {
  12. int a,b;
  13. scanf("%d%d",&a,&b);
  14. swap(a,b);
  15. printf("a=%d,b=%d\n",a,b);
  16. return 0;
  17. }

 正确2:引用变量必须用c++

  1. #include<cstdio>
  2. #include<iostream>
  3. using namespace std;
  4. void swap(int &p,int &q)
  5. {
  6. int t;
  7. t=p;
  8. p=q;
  9. q=t;
  10. }
  11. int main()
  12. {
  13. int a,b;
  14. cin>>a>>b;
  15. swap(a,b);
  16. count<<"a="<<a<<","<<"b="<<b<<endl;
  17. return 0;
  18. }

 二分查找法(时间效率的问题)

举例:数组a中存放从小到大排好序的n个整数,查找给定值k在数组中下标;若查找失败,返回-1

  1. //函数部分
  2. int BitSearch(int a[],int n,int k)
  3. {
  4. int low=0,high=n-1,mid,found=0;
  5. while((low<=high)&&(found==0))
  6. {
  7. mid=(low+high)/2;
  8. if(k>a[mid])
  9. low=mid+1;
  10. else if(k==a[mid])
  11. found=1;
  12. else
  13. high=mid-1;
  14. }
  15. if(found==1)
  16. return (mid);
  17. else
  18. return(-1);
  19. }

 若n=15,此方法最多找四次(树的结构),而若一个一个数据对比需要找15次,对比之下,二分查找法时间效率会快很多。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/202093?site
推荐阅读
相关标签
  

闽ICP备14008679号