线性表的就地逆置用c语言实现
时间: 2023-10-24 09:04:46 浏览: 46
以下是线性表的就地逆置的C语言实现:
```c
#include <stdio.h>
#define MAXSIZE 100 // 定义线性表的最大长度
typedef struct {
int data[MAXSIZE]; // 存储线性表元素的数组
int length; // 线性表当前长度
} SeqList;
void InitList(SeqList *L) {
// 初始化线性表
L->length = 0;
}
void CreateList(SeqList *L, int n) {
// 创建线性表
int i;
printf("请依次输入%d个整数作为线性表的元素:", n);
for (i = 0; i < n; i++) {
scanf("%d", &L->data[i]);
}
L->length = n;
}
void ReverseList(SeqList *L) {
// 就地逆置线性表
int i, temp;
for (i = 0; i < L->length/2; i++) {
temp = L->data[i];
L->data[i] = L->data[L->length-1-i];
L->data[L->length-1-i] = temp;
}
}
void PrintList(SeqList L) {
// 输出线性表的元素
int i;
printf("线性表的元素为:");
for (i = 0; i < L.length; i++) {
printf("%d ", L.data[i]);
}
printf("\n");
}
int main() {
SeqList L;
int n;
printf("请输入线性表的长度:");
scanf("%d", &n);
InitList(&L);
CreateList(&L, n);
PrintList(L);
ReverseList(&L);
printf("逆置后的线性表为:");
PrintList(L);
return 0;
}
```
示例输出:
```
请输入线性表的长度:5
请依次输入5个整数作为线性表的元素:1 2 3 4 5
线性表的元素为:1 2 3 4 5
逆置后的线性表为:5 4 3 2 1
```