8578 顺序表逆置

### 思路
1. 初始化顺序表并插入元素。
2. 输出逆置前的顺序表元素列表。
3. 逆置顺序表。
4. 输出逆置后的顺序表元素列表。

### 伪代码
1. 初始化顺序表 `L`。
2. 读取顺序表的元素个数 `n`。
3. 读取顺序表的各元素并插入到 `L` 中。
4. 输出逆置前的顺序表元素列表。
5. 逆置顺序表:
   - 使用双指针法,一个指针从表头开始,一个指针从表尾开始,交换两个指针所指向的元素,直到两个指针相遇。
6. 输出逆置后的顺序表元素列表。

### C++代码

#include <iostream>
#include <malloc.h>
using namespace std;

#define OK 1
#define ERROR 0
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define ElemType int

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

Status InitList_Sq(SqList &L) {
    L.elem = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType));
    if (!L.elem) return OK;
    L.length = 0;
    L.listsize = LIST_INIT_SIZE;
    return OK;
}

Status ListInsert_Sq(SqList &L, int i, ElemType e) {
    if (i < 1 || i > L.length + 1) return ERROR;
    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]);
    for (ElemType *p = &(L.elem[L.length - 1]); p >= q; --p) *(p + 1) = *p;
    *q = e;
    ++L.length;
    return OK;
}

Status ListDelete_Sq(SqList &L, int i, ElemType &e) {
    if (i < 1 || i > L.length) return ERROR;
    ElemType *p = &(L.elem[i - 1]);
    e = *p;
    for (ElemType *q = p + 1; q <= L.elem + L.length - 1; ++q) *(q - 1) = *q;
    --L.length;
    return OK;
}

void ReverseList_Sq(SqList &L) {
    int i = 0, j = L.length - 1;
    while (i < j) {
        ElemType temp = L.elem[i];
        L.elem[i] = L.elem[j];
        L.elem[j] = temp;
        i++;
        j--;
    }
}

void PrintList_Sq(SqList &L) {
    for (int i = 0; i < L.length; i++) {
        cout << L.elem[i] << " ";
    }
    cout << endl;
}

int main() {
    SqList L;
    InitList_Sq(L);

    int n;
    cin >> n;
    for (int i = 1; i <= n; i++) {
        ElemType e;
        cin >> e;
        ListInsert_Sq(L, i, e);
    }

    cout << "The List is:";
    PrintList_Sq(L);

    ReverseList_Sq(L);

    cout << "The turned List is:";
    PrintList_Sq(L);

    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值