天天看点

顺序表逆置

#include<stdio.h>
#include<malloc.h>
#define OK 1
#define ERROR 0
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define ElemType int

typedef struct
{
    int *elem;
    int length;
    int listsize;
}SqList;

int InitList_Sq(SqList &L)
{  // 算法2.3
  // 构造一个空的线性表L。
  L.elem = (ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
  if (!L.elem) {
      printf("NO1");
      return OK; }       // 存储分配失败
  L.length = 0;                  // 空表长度为0
  L.listsize = LIST_INIT_SIZE;   // 初始存储容量
  return OK;
} // InitList_Sq

int ListInsert_Sq(SqList &L, int i, ElemType e)
{  // 算法2.4
  // 在顺序线性表L的第i个元素之前插入新的元素e,
  // i的合法值为1≤i≤ListLength_Sq(L)+1
  ElemType *p;
  if (i < 1 || i > L.length+1) return ERROR;  // i值不合法
  if (L.length >= L.listsize) {   // 当前存储空间已满,增加容量
    ElemType *newbase = (ElemType *)realloc(L.elem,
                  (L.listsize+LISTINCREMENT)*sizeof (ElemType));
    if (!newbase) return ERROR;   // 存储分配失败
    L.elem = newbase;             // 新基址
    L.listsize += LISTINCREMENT;  // 增加存储容量
  }
  ElemType *q = &(L.elem[i-1]);   // q为插入位置
  for (p = &(L.elem[L.length-1]); p>=q; --p) *(p+1) = *p;
                                  // 插入位置及之后的元素右移
  *q = e;       // 插入e
  ++L.length;   // 表长增1
  return OK;
} // ListInsert_Sq

int Load_Sq(SqList &L)
{
    int i;
    if(!L.length)
    {
        printf("This List is empty");
        return ERROR;

    }
    else
    {
        for(i=0;i<L.length;i++)
        printf("%d ",L.elem[i]);

    }
    printf("\n");
    return OK;

}

int swap(SqList &L,int n)
{
    int i,j,temp;
    for(i=0,j=n-1;j>i;i++,j--)
    {
        temp=L.elem[i];
        L.elem[i]=L.elem[j];
        L.elem[j]=temp;

    }
    return OK;
}

int main()
{
    SqList T;
    int n,i;
    ElemType x;
    scanf("%d",&n);
    InitList_Sq(T);
    for(i=1;i<n+1;i++)
    {
        scanf("%d",&x);
        ListInsert_Sq(T,i,x);

    }
    printf("The List is:");
    Load_Sq(T);
    swap(T,n);
    printf("The turned List is:");
    Load_Sq(T);
    return 0 ;
}
           

   输入:

第一行:输入顺序表的元素个数
      

第二行:输入顺序表的各元素,用空格分开

输出:

第一行:逆置前的顺序表元素列表

第二行:逆置后的顺序表元素列表

继续阅读