C语言数据结构,实现线性表的顺序存储定义,完成顺序表的创建、插入、删除、查找、排序等常用操作,完成两个有序线性表的合并,要求同样的数据元素只出现一次。
时间: 2024-09-15 19:08:52 浏览: 67
C语言中,线性表的顺序存储通常是指将数据元素按照一定的顺序存储在一维数组中。为了实现顺序表,我们可以这样做:
1. **定义结构体**:
```c
typedef struct {
int *data; // 存储数据的指针
int size; // 当前元素个数
int capacity; // 容量,即数组长度
} SeqList;
```
2. **初始化顺序表**:
```c
SeqList* createList(int capacity) {
SeqList *list = (SeqList*)malloc(sizeof(SeqList));
list->data = malloc(capacity * sizeof(int));
list->size = 0;
list->capacity = capacity;
return list;
}
```
3. **插入操作** (如在尾部插入):
```c
void insert(SeqList *list, int value) {
if (list->size == list->capacity) {
list->capacity *= 2; // 若满,则扩大容量
list->data = realloc(list->data, list->capacity * sizeof(int));
}
list->data[list->size++] = value;
}
```
4. **删除操作** (如删除第一个值为value的元素):
```c
void delete(SeqList *list, int value) {
for (int i = 0; i < list->size; i++) {
if (list->data[i] == value) {
memmove(&list->data[i], &list->data[i+1], (list->size-i-1)*sizeof(int));
list->size--;
break;
}
}
}
```
5. **查找操作**:
```c
int search(SeqList *list, int value) {
for (int i = 0; i < list->size; i++) {
if (list->data[i] == value)
return i;
}
return -1; // 如果未找到则返回-1
}
```
6. **排序操作** (这里假设使用简单的冒泡排序):
```c
void sort(SeqList *list) {
for (int i = 0; i < list->size - 1; i++) {
for (int j = 0; j < list->size - i - 1; j++) {
if (list->data[j] > list->data[j+1]) {
int temp = list->data[j];
list->data[j] = list->data[j+1];
list->data[j+1] = temp;
}
}
}
}
```
7. **合并两个有序线性表**:
```c
SeqList* mergeSortedLists(SeqList *list1, SeqList *list2) {
SeqList *mergedList = createList(list1->size + list2->size);
int i = 0, j = 0;
while (i < list1->size && j < list2->size) {
if (list1->data[i] <= list2->data[j])
insert(mergedList, list1->data[i++]);
else
insert(mergedList, list2->data[j++]);
}
while (i < list1->size)
insert(mergedList, list1->data[i++]);
while (j < list2->size)
insert(mergedList, list2->data[j++]);
return mergedList;
}
```
阅读全文