用c语言写份将顺序表的元素调整为前奇后偶的代码
时间: 2024-03-23 09:41:17 浏览: 9
以下是用C语言实现将顺序表的元素调整为前奇后偶的代码:
```c
#include <stdio.h>
#define MAXSIZE 100 // 定义顺序表的最大长度
typedef struct {
int data[MAXSIZE];
int length;
} SqList;
// 初始化顺序表
void InitList(SqList *L) {
L->length = 0;
}
// 插入元素
int ListInsert(SqList *L, int pos, int elem) {
if (pos < 1 || pos > L->length + 1 || L->length == MAXSIZE) {
return 0;
}
for (int i = L->length; i >= pos; i--) {
L->data[i] = L->data[i - 1];
}
L->data[pos - 1] = elem;
L->length++;
return 1;
}
// 调整元素顺序
void AdjustList(SqList *L) {
int i = 0, j = L->length - 1;
while (i < j) {
// 从前往后找到第一个偶数
while (i < j && L->data[i] % 2 != 0) {
i++;
}
// 从后往前找到第一个奇数
while (i < j && L->data[j] % 2 == 0) {
j--;
}
// 交换奇偶位置
int temp = L->data[i];
L->data[i] = L->data[j];
L->data[j] = temp;
}
}
// 输出顺序表
void PrintList(SqList L) {
for (int i = 0; i < L.length; i++) {
printf("%d ", L.data[i]);
}
printf("\n");
}
int main() {
SqList L;
InitList(&L);
ListInsert(&L, 1, 1);
ListInsert(&L, 2, 2);
ListInsert(&L, 3, 3);
ListInsert(&L, 4, 4);
ListInsert(&L, 5, 5);
ListInsert(&L, 6, 6);
ListInsert(&L, 7, 7);
ListInsert(&L, 8, 8);
printf("调整前:");
PrintList(L);
AdjustList(&L);
printf("调整后:");
PrintList(L);
return 0;
}
```
代码的主要思路是通过两个指针 i 和 j 分别从前往后和从后往前遍历顺序表,找到第一个偶数和第一个奇数,然后交换它们的位置,直到 i >= j 为止,这样就能保证顺序表前面是奇数,后面是偶数。