在顺序表中插入,删除,查找指定元素,合并两个顺序表,用C语言程序
时间: 2023-05-12 08:04:21 浏览: 88
C语言实现顺序表的合并
来实现这些操作,你可以使用数组来表示顺序表。以下是一个简单的示例代码:
```c
#include <stdio.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int length;
} SeqList;
void init(SeqList *list) {
list->length = 0;
}
void insert(SeqList *list, int index, int value) {
if (index < 0 || index > list->length || list->length == MAX_SIZE) {
printf("Invalid index or list is full.\n");
return;
}
for (int i = list->length - 1; i >= index; i--) {
list->data[i + 1] = list->data[i];
}
list->data[index] = value;
list->length++;
}
void remove(SeqList *list, int index) {
if (index < 0 || index >= list->length) {
printf("Invalid index.\n");
return;
}
for (int i = index; i < list->length - 1; i++) {
list->data[i] = list->data[i + 1];
}
list->length--;
}
int search(SeqList *list, int value) {
for (int i = 0; i < list->length; i++) {
if (list->data[i] == value) {
return i;
}
}
return -1;
}
void merge(SeqList *list1, SeqList *list2, SeqList *result) {
int i = 0, j = 0, k = 0;
while (i < list1->length && j < list2->length) {
if (list1->data[i] < list2->data[j]) {
result->data[k++] = list1->data[i++];
} else {
result->data[k++] = list2->data[j++];
}
}
while (i < list1->length) {
result->data[k++] = list1->data[i++];
}
while (j < list2->length) {
result->data[k++] = list2->data[j++];
}
result->length = k;
}
int main() {
SeqList list1, list2, result;
init(&list1);
init(&list2);
init(&result);
insert(&list1, 0, 1);
insert(&list1, 1, 3);
insert(&list1, 2, 5);
insert(&list2, 0, 2);
insert(&list2, 1, 4);
insert(&list2, 2, 6);
merge(&list1, &list2, &result);
for (int i = 0; i < result.length; i++) {
printf("%d ", result.data[i]);
}
printf("\n");
remove(&result, 2);
int index = search(&result, 4);
if (index != -1) {
printf("Found at index %d.\n", index);
} else {
printf("Not found.\n");
}
return 0;
}
```
这个程序实现了顺序表的插入、删除、查找和合并操作。你可以根据需要进行修改和扩展。
阅读全文