scau 8578 顺序表逆置

       下周小测,借着周末回头复习一下之前写过的代码。这道题还是蛮简单的,题目有给顺序表的基本操作代码,但题目所给的基本操作代码和课本上、我们之前写过的题有点点小不一样,题目用的是指针,指针一直学的迷迷糊糊,我看起来好累,就没有细细去看了哈哈哈,可别学我!遇到问题还是得刨根问底把它搞懂,特别是指针,指来指去的特别容易乱,但它也是重中之重,一定要学好!

       这道题没啥难度,动手找逆置规律即可,列个小数组,找第一个和最后一个、第二个和倒数第二个下标……的关系,我的数组喜欢从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;
}

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值