下周小测,借着周末回头复习一下之前写过的代码。这道题还是蛮简单的,题目有给顺序表的基本操作代码,但题目所给的基本操作代码和课本上、我们之前写过的题有点点小不一样,题目用的是指针,指针一直学的迷迷糊糊,我看起来好累,就没有细细去看了哈哈哈,可别学我!遇到问题还是得刨根问底把它搞懂,特别是指针,指来指去的特别容易乱,但它也是重中之重,一定要学好!
这道题没啥难度,动手找逆置规律即可,列个小数组,找第一个和最后一个、第二个和倒数第二个下标……的关系,我的数组喜欢从1开始,这样比较好定位,规律也蛮简单。
void nizhi(SqList &L,int n)//n为顺序表的长度
{
int j;
for(j=1;j<=n/2;j++)//逆置的规律
{
int temp;
temp=L.elem[j];
L.elem[j]=L.elem[n-j+1];
L.elem[n-j+1]=temp;
}
cout << "The turned List is:";//建议把输出单独拿出来做一个函数,提高代码的通用性
for(int i=1;i<=n;i++)
{
cout << L.elem[i] << ' ';
}
}
下面是全部代码
#include <iostream>
#include <cstdio>
#include <cstdlib>
#define OK 1
#define ERROR 0
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define ElemType int
using namespace std;
typedef int Status;
typedef struct
{
int *elem;
int length;
int listsize;
} SqList;
Status InitList_Sq(SqList &L)
{
// 算法2.3
// 构造一个空的线性表L。
L.elem = (ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
if (!L.elem) return OK; // 存储分配失败
L.length = 0; // 空表长度为0
L.listsize = LIST_INIT_SIZE; // 初始存储容量
return OK;
} // InitList_Sq
void nizhi(SqList &L,int n)
{
int j;
for(j=1;j<=n/2;j++)
{
int temp;
temp=L.elem[j];
L.elem[j]=L.elem[n-j+1];
L.elem[n-j+1]=temp;
}
cout << "The turned List is:";
for(int i=1;i<=n;i++)
{
cout << L.elem[i] << ' ';
}
}
int main()
{
std::ios::sync_with_stdio(false);//提高cin和cout的速度
SqList L;
InitList_Sq(L);
int i,n;
cin >> n;
for(i=1;i<=n;i++)
{
cin >> L.elem[i];
}
cout << "The List is:";
for(i=1;i<=n;i++)
{
cout << L.elem[i] << ' ';
}
cout << endl;
nizhi(L,n);
return 0;
}