两个函数实现在有序的顺序表中查找元素;如果找到了,打印元素在顺序表中位置;如果没有找到,把元素插入到顺序表的合适位置上,使用顺序表仍然有序。c语言
时间: 2024-10-10 07:03:00 浏览: 47
在C语言中,你可以使用线性搜索(顺序查找)来查找元素并保持列表有序。首先,我们可以创建一个函数`search_insert`来完成这个任务。以下是基本的步骤:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义顺序表结构体
typedef struct {
int data;
struct Node* next;
} Node;
// 函数声明
Node* search_insert(Node** head, int target);
// 线性搜索,查找目标元素的位置
int linear_search(Node* head, int target) {
int position = 0;
Node* current = *head;
while (current != NULL && current->data < target) {
++position;
current = current->next;
}
return position;
}
// 插入函数,如果找到直接返回,未找到则插入到正确位置
Node* search_insert(Node** head, int target) {
if (*head == NULL || target <= (*head)->data) {
// 如果链表为空或目标小于等于头节点,插入新节点作为头节点
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = target;
newNode->next = *head;
*head = newNode;
return newNode;
} else {
// 使用线性搜索找到插入位置
int position = linear_search(*head, target);
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = target;
newNode->next = (*head)->next;
// 将链表从插入位置断开
(*head)->next = newNode->next;
// 连接新节点到正确位置
for (int i = 0; i < position - 1; ++i) {
(*head) = (*head)->next;
}
return newNode;
}
}
int main() {
Node* list = NULL;
// 初始化列表... (这里省略添加元素的过程)
int target = 50;
Node* inserted = search_insert(&list, target);
if (inserted == NULL) {
printf("元素 %d 已经在列表中\n", target);
} else {
printf("元素 %d 插入到了第 %d 位\n", target, linear_search(list, target));
}
// 遍历并打印整个有序列表
Node* temp = list;
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
return 0;
}
```
阅读全文
相关推荐


















