线性表链式存储结构下基本操作的实现(初始化、建表、取值、查找、插入、删除、两个非递减有序链表的归并等)。C语言代码及运行结果
时间: 2024-10-08 09:26:15 浏览: 59
线性表的链式存储结构是一种动态数据结构,它的基本操作包括:
1. 初始化(创建空链表):
```c
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createList() {
Node* head = NULL;
return head;
}
```
2. 建表(插入元素到链表头部):
```c
void insertAtBegin(Node** head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = *head;
*head = newNode;
}
```
3. 取值(访问节点数据):
```c
int getValue(Node* node) {
if (node != NULL) {
return node->data;
}
else {
printf("Invalid node.\n");
return -1; // 返回错误码
}
}
```
4. 查找(遍历寻找特定值):
```c
Node* search(Node* head, int value) {
Node* current = head;
while (current != NULL) {
if (current->data == value) {
return current;
}
current = current->next;
}
return NULL;
}
```
5. 插入(在指定位置插入元素):
```c
void insertAfter(Node** head, int value, int position) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
if (*head == NULL || position == 0) {
insertAtBegin(head, value);
} else {
for (int i = 0; i < position - 1 && *head != NULL; i++) {
*head = (*head)->next;
}
if (*head != NULL) {
newNode->next = (*head)->next;
(*head)->next = newNode;
} else {
printf("Invalid position.\n");
}
}
}
```
6. 删除(移除某个元素):
```c
void deleteValue(Node** head, int value) {
if (*head == NULL) {
return;
}
if ((*head)->data == value) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
return;
}
Node* current = *head;
while (current->next != NULL && current->next->data != value) {
current = current->next;
}
if (current->next != NULL) {
Node* temp = current->next;
current->next = temp->next;
free(temp);
} else {
printf("Element not found.\n");
}
}
```
7. 归并两个非递减有序链表(合并两个已排序链表):
```c
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;
}
}
```
以上代码只是基本示例,并未包含异常处理。在实际应用中,需要考虑内存管理和其他边界条件。
阅读全文