天天看点

顺序表的就地逆置

        • 顺序表的就地逆置

顺序表的就地逆置

例:编写一个函数,实现顺序表的就地逆置,即利用原表的存储空间将顺序表逆置。

题目分析:

要实现长度为length的顺序表的就地逆置,需要一个临时变量tmp作为缓冲区,同时要设置两个指针变量low和high分别指向顺序表的首尾。操作如下:

(1)先将low指向的内容放入缓冲区tmp中。

(2)再将high指向的内容放到low指向的内存单元。

(3)将缓冲区的内容放入high指向的内存单元。

(4)low++,high–,重复(1)(2)(3)步的操作,共执行[length/2]次

通俗来讲就是顺序表中对称元素的交换。

#include"stdio.h"
    #define  MAXSIZE 10
    typedef struct {
           int *base;
           int length;
    }sqlist;

    //就地逆置函数
    reverseSQ(sqlist *l)
    {
          int low=,high=length-;
          int tmp,i;
          for(i=;i<l->length/;i++)
          {
              tmp=l->base[low];
              l->base[low]=l->base[high];
              l->base[high]=tmp;       //注意表中元素的调用
              low++;
              high++;
          }
    }

    main()
    {
       sqlist l;           //定义一个表
       int a,i=;
       //创建一个顺序表
       l.base=(int*)malloc(sizeof(int)*MAXSIZE);
       l.length=;

       //输入数据
       printf("Please input below 10 integer into the sqlist\n");
       printf("Type -1 for stopping input\n");
       scanf("%d",&a);
       while(a!=-&&i<=)
       {
           l.base[i]=a;          //数据的输入
           l.length++;
           i++;
           scanf("%d",&a);
       }

       //输出原顺序表中的数据
       printf("The contents of the sqlist are:\n");
       for(i=;i<l.length;i++)
           printf("%d",l.base[i]);
           printf("\n");

           //逆置
           reverseSQ(&l);

           //输出逆置后的数据
            printf("The contents of the reversed sqlist are:\n");
       for(i=;i<l.length;i++)
           printf("%d",l.base[i]);
           getche();
    }
本程序中-不能作为输入数据
           

继续阅读