以下是使用线性表 ADT 基本运算实现整数反转的 C 语言代码:

#include <stdio.h>

#define MAX_SIZE 100

typedef struct {
    int data[MAX_SIZE];
    int length;
} List;

void InitList(List *L) {
    L->length = 0;
}

void InsertList(List *L, int pos, int value) {
    if (pos < 1 || pos > L->length + 1) {
        printf('Error: Invalid position.\n');
        return;
    }
    if (L->length == MAX_SIZE) {
        printf('Error: List is full.\n');
        return;
    }
    for (int i = L->length; i >= pos; i--) {
        L->data[i] = L->data[i - 1];
    }
    L->data[pos - 1] = value;
    L->length++;
}

void ReverseList(List *L) {
    int left = 1;
    int right = L->length;
    while (left < right) {
        int temp = L->data[left - 1];
        L->data[left - 1] = L->data[right - 1];
        L->data[right - 1] = temp;
        left++;
        right--;
    }
}

void PrintList(List *L) {
    for (int i = 0; i < L->length; i++) {
        printf('%d ', L->data[i]);
    }
    printf('\n');
}

int main() {
    List L;
    int n;
    printf('Enter the number of elements: ');
    scanf('%d', &n);
    printf('Enter the elements: ');
    for (int i = 0; i < n; i++) {
        int value;
        scanf('%d', &value);
        InsertList(&L, i + 1, value);
    }
    printf('Original List: ');
    PrintList(&L);
    ReverseList(&L);
    printf('Reversed List: ');
    PrintList(&L);
    return 0;
}

在这个代码中,我们使用了线性表 ADT 的基本运算,包括初始化线性表、插入元素和反转线性表。用户可以键入整数来创建一个线性表,并输出反转后的线性表。

C语言线性表ADT实现整数反转 - 模块化编程

原文地址: https://www.cveoy.top/t/topic/zsK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录