c语言设计一个有序顺序表,实现以下操作: 1.将元素x插入表中并保持有序; 2.查找值为x的元素,若找到则将其删除; 3.输出表中所有元素。
时间: 2024-09-26 10:06:30 浏览: 33
在C语言中,我们可以使用链表结构来设计一个动态的有序顺序表,这里假设我们使用的是结构体作为节点,并实现了相应的函数来支持上述操作:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义一个结构体表示列表节点
typedef struct Node {
int data; // 数据域
struct Node* next; // 指向下一个节点的指针
} Node;
// 初始化一个空链表
Node* createList() {
return (Node*)malloc(sizeof(Node));
}
// 插入元素x保持有序
void insert(int x, Node** head) {
Node* newNode = createList();
newNode->data = x;
if (*head == NULL || newNode->data <= (*head)->data) {
newNode->next = *head;
*head = newNode;
} else {
Node* current = *head;
while (current->next != NULL && newNode->data > current->next->data) {
current = current->next;
}
newNode->next = current->next;
current->next = newNode;
}
}
// 查找并删除值为x的元素
void deleteElement(int x, Node** head) {
if (*head == NULL) return;
if ((*head)->data == x) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
return;
}
Node* current = *head;
while (current->next != NULL && current->next->data != x) {
current = current->next;
}
if (current->next != NULL) {
Node* temp = current->next;
current->next = temp->next;
free(temp);
}
}
// 遍历打印链表
void printList(Node* head) {
if (head == NULL) return;
printf("Sorted List: ");
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
Node* listHead = createList(); // 创建初始为空的链表
// 插入示例
insert(5, &listHead); // [5]
insert(2, &listHead); // [2, 5]
insert(8, &listHead); // [2, 5, 8]
// 打印链表
printList(listHead); // 输出: Sorted List: 2 5 8
// 删除示例
deleteElement(5, &listHead); // [2, 8]
printList(listHead); // 输出: Sorted List: 2 8
return 0;
}
```
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)