实现线性表的顺序存储定义,完成顺序表的创建、插入、删除、查找、排序等常用操作,完成两个有序线性表的合并,要求同样的数据元素只出现一次。
时间: 2023-06-19 18:10:43 浏览: 63
线性表的顺序存储的实现
4星 · 用户满意度95%
顺序存储定义:
```c
#define MAXSIZE 100
typedef int ElementType;
typedef struct {
ElementType data[MAXSIZE];
int length;
} SeqList;
```
创建顺序表:
```c
void CreateList(SeqList *L, ElementType arr[], int n) {
int i;
for (i = 0; i < n; i++) {
L->data[i] = arr[i];
}
L->length = n;
}
```
插入操作:
```c
int InsertList(SeqList *L, int pos, ElementType x) {
int i;
if (pos < 1 || pos > L->length + 1 || L->length == MAXSIZE) {
return 0;
}
for (i = L->length; i >= pos; i--) {
L->data[i] = L->data[i - 1];
}
L->data[pos - 1] = x;
L->length++;
return 1;
}
```
删除操作:
```c
int DeleteList(SeqList *L, int pos, ElementType *x) {
int i;
if (pos < 1 || pos > L->length) {
return 0;
}
*x = L->data[pos - 1];
for (i = pos; i < L->length; i++) {
L->data[i - 1] = L->data[i];
}
L->length--;
return 1;
}
```
查找操作:
```c
int SearchList(SeqList *L, ElementType x) {
int i;
for (i = 0; i < L->length; i++) {
if (L->data[i] == x) {
return i + 1;
}
}
return 0;
}
```
排序操作:
```c
void SortList(SeqList *L) {
int i, j;
ElementType temp;
for (i = 0; i < L->length - 1; i++) {
for (j = i + 1; j < L->length; j++) {
if (L->data[i] > L->data[j]) {
temp = L->data[i];
L->data[i] = L->data[j];
L->data[j] = temp;
}
}
}
}
```
合并操作:
```c
void MergeList(SeqList *L1, SeqList *L2, SeqList *L3) {
int i = 0, j = 0, k = 0;
while (i < L1->length && j < L2->length) {
if (L1->data[i] < L2->data[j]) {
L3->data[k++] = L1->data[i++];
} else if (L1->data[i] > L2->data[j]) {
L3->data[k++] = L2->data[j++];
} else {
L3->data[k++] = L1->data[i++];
j++;
}
}
while (i < L1->length) {
L3->data[k++] = L1->data[i++];
}
while (j < L2->length) {
L3->data[k++] = L2->data[j++];
}
L3->length = k;
// 去除重复元素
for (i = 0, k = 0; i < L3->length; i++) {
if (L3->data[i] != L3->data[i+1]) {
L3->data[k++] = L3->data[i];
}
}
L3->length = k;
}
```
阅读全文