写一个满足线性表顺序存储结构下基本操作的实现(初始化、建表、取值、查找、插入、删除、两个非递减有序链表的归并等)。 线性表链式存储结构下基本操作的实现(初始化、建表、取值、查找、插入、删除、两个非递减有序链表的归并等)的c语言代码、
时间: 2024-09-20 07:14:56 浏览: 40
数据结构 线性表 顺序表基本操作
4星 · 用户满意度95%
在C语言中,我们可以使用结构体和指针来实现线性表的链式存储结构。这里给出一个简单的示例,包含了上述的基本操作:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
typedef struct Node {
int data;
struct Node* next;
} Node;
// 初始化一个空链表
Node* initializeList() {
return NULL;
}
// 创建链表
Node* createList(int arr[], int size) {
Node* head = initializeList();
for (int i = 0; i < size; i++) {
if (!head) {
head = (Node*)malloc(sizeof(Node));
head->data = arr[i];
head->next = NULL;
} else {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = arr[i];
newNode->next = head;
head = newNode;
}
}
return head;
}
// 取值操作(访问)
int getValue(Node* node, int index) {
if (index < 0 || index >= node->next != NULL)
return -1; // 如果索引越界,返回错误码
Node* temp = node;
for (int i = 0; i < index; i++)
temp = temp->next;
return temp->data;
}
// 查找操作
Node* search(Node* head, int key) {
Node* current = head;
while (current != NULL && current->data != key)
current = current->next;
return current;
}
// 插入操作
void insert(Node** head, int value, int position) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = NULL;
if (position == 0) { // 插入到头部
newNode->next = *head;
*head = newNode;
} else {
Node* prev = *head;
int i;
for (i = 0; i < position - 1 && prev->next != NULL; i++)
prev = prev->next;
if (prev->next != NULL)
newNode->next = prev->next;
prev->next = newNode;
}
}
// 删除操作
void deleteElement(Node** head, int key) {
if (*head == NULL) return;
if ((*head)->data == key) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
return;
}
Node* curr = *head, *prev = NULL;
while (curr != NULL && curr->data != key) {
prev = curr;
curr = curr->next;
}
if (curr == NULL) return;
prev->next = curr->next;
free(curr);
}
// 归并两个非递减有序链表
Node* mergeSortedLists(Node* list1, Node* list2) {
if (list1 == NULL) return list2;
if (list2 == NULL) return list1;
if (list1->data <= list2->data) {
list1->next = mergeSortedLists(list1->next, list2);
return list1;
} else {
list2->next = mergeSortedLists(list1, list2->next);
return list2;
}
}
// 打印链表
void printList(Node* head) {
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
}
int main() {
int arr[] = {1, 3, 5, 7};
int size = sizeof(arr) / sizeof(arr[0]);
Node* list = createList(arr, size);
// 示例用法
printList(list); // 输出: 1 -> 3 -> 5 -> 7 -> NULL
// ... 其他操作...
return 0;
}
```
阅读全文