Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2501252
  • 博文数量: 308
  • 博客积分: 5547
  • 博客等级: 大校
  • 技术积分: 3782
  • 用 户 组: 普通用户
  • 注册时间: 2009-11-24 09:47
个人简介

hello world.

文章分类

全部博文(308)

分类: C/C++

2011-06-09 08:33:22

    编写一个函数,实现顺序表的就地逆置,也就是说利用原表的存储空间将顺序表(a1,a2...an)逆置为(an,an-1...a2,a1)。
    让我们能想到的是,利用使用三个指针,分别指向开始,中间,结束。元素。通过中间元素实现,开始元素和结束元素的交换,然后,开始元素的指针加一,结束元素的指针减一,这样循环下去,当开始元素的指针不小于中间元素指针时停止。
    代码如下:
  1. #include <stdio.h>
  2. #include <stdlib.h>

  3. typedef struct{
  4.      int *base;
  5.      int length;
  6. } sqlist;

  7. void reverseSQ(sqlist *l)
  8. {
  9.      int low = 0, high = l->length - 1;
  10.      int buf, i, count = l->length / 2;
  11.      for(i=0; i<count; i++){
  12.      buf = l->base[low];
  13.      l->base[low++] = l->base[high];
  14.      l->base[high--] = buf;
  15.      }
  16. }

  17. void printSQ(sqlist *l)
  18. {
  19.      int i = 0;
  20.      for(i=0; i<l->length; i++)
  21.      printf("%d ",l->base[i]);
  22.      printf("\n");
  23. }

  24. int main(int argc, char *argv[])
  25. {
  26.      sqlist l;
  27.      int a,i = 0;
  28.      int cnt = 0;
  29.      
  30.      printf("please input count num:");
  31.      scanf("%d",&cnt);
  32.      l.base = (int *)malloc(sizeof(int) * cnt);
  33.      l.length = 0;
  34.      
  35.      while(i < cnt){
  36.      scanf("%d",&a);
  37.      l.base[i++] = a;
  38.      l.length++;
  39.      }    
  40.      printf("the contents of the sqlist are\n");
  41.      printSQ(&l);
  42.      reverseSQ(&l);
  43.      printf("the contents of the reversed sqlist are\n");
  44.      printSQ(&l);
  45.      free(l.base); //释放内存
  46.      return 0;
  47. }
运行结果:
peng@ubuntu:~/src/test/c/suanfa/miaoqu$ gcc -Wall 7.1-1.c  
peng@ubuntu:~/src/test/c/suanfa/miaoqu$ ./a.out 
please input count num:5
1 2 3 4 5
the contents of the sqlist are
1 2 3 4 5
the contents of the reversed sqlist are
5 4 3 2 1

阅读(12825) | 评论(0) | 转发(1) |
0

上一篇:选美比赛

下一篇:删除日志-Shell编程

给主人留下些什么吧!~~