线性表中的顺序表逆置算法:

假设有10个元素,在申请空间的时候需要申请11个位置(注意:一维数组中有结束符,所以多申请一位空间),

在逆置过程中需要考虑到申请12位空间

10 20 30 40

逆置时:

10 20 30 40  

先将所有项向后移动一位:

  10 20 30 40

将最后一位的值附在第一位上:

40 10 20 30

 

然后不断重复过程:

40   10 20 30

以下为实现逆置并输出的全部代码:

#include<stdio.h>
#include<stdlib.h>
#define ERROR 0
#define OK 1
#define overflow 2 //表示上溢
#define underflow 3 //表示下溢
#define NotPresent 4  //表示元素不存在
#define DupLicate 5 //表示有重复元素
typedef int ElemType;//建立顺序表
typedef struct
{
int n;
int maxLength;
ElemType *element;
}SeqList;
typedef int Status;


Status Inverse(SeqList *L,int i)//就地逆置
{
    int a,j;
    if(L->n+1>L->maxLength)
        return ERROR;
    for(a=L->n;i<a;i++)
    {
        for(j=L->n;j>=i;j--)
        {
         L->element[j+1]=L->element[j];//数组元素向后移一位
        }
    L->element[i]=L->element[L->n];//给第一个元素附最后一位的值
    }
    return OK;
}

 

Status Output(SeqList L)//输出

int i;
if(!L.n)
return ERROR; //判断顺序表是否为空
for(i=0;i<L.n;i++)
 printf("%d",L.element[i]);
return OK;
}

Status Init(SeqList *L,int mSize)//初始化
{
L->maxLength=mSize;
L->n=0;
L->element=(ElemType *)malloc(sizeof(ElemType)*mSize);//动态生成一维数组
if(!L->element)
 return ERROR;
return OK;
}

Status Insert(SeqList *L,int i,ElemType m)//插入数据

int j;
if(!L->element) 
return ERROR;
if(L->n==L->maxLength)  //判断储存空间是否已满
return ERROR;
for(j=L->n;j>i;j--)
L->element[j]=L->element[j-1];
L->element[i]=m;
L->n=L->n+1;
return OK;
}

void main()
{
    int i;
SeqList list;
Init(&list,12); //对顺序表进行初始化处理
for(i=0;i<=9;i++) //利用for循环来插入数据,循环操作10次可插入10个数字
Insert(&list,i,i);
printf("\nthe Seqlist is:");
Output(list); 
Inverse(&list,0);
printf("\nthe Inverse Seqlist is:");
Output(list); 
}

运行结果如下:

顺序表的就地逆置

相关文章: