用C语言编写一个完整的程序代码,实现线性表{1,4,5,2,3}的顺序存储定义,先后完成顺序表的创建、插入0、删除5、从小到大排序、查找3等常用操作。(保证程序完整且能成功运行输出结果)
时间: 2024-12-02 19:20:13 浏览: 1
```c
#include <stdio.h>
#include <stdlib.h>
// 定义顺序表结构体
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建顺序表
Node* create_list(int arr[], int size) {
Node* head = (Node*)malloc(sizeof(Node));
if (!head) {
printf("Memory allocation failed.\n");
return NULL;
}
head->data = arr[0];
head->next = NULL;
for (int i = 1; i < size; i++) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = arr[i];
newNode->next = head->next;
head->next = newNode;
}
return head;
}
// 插入元素0
void insert_at_start(Node** head, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = *head;
*head = newNode;
}
// 删除节点
void delete_node(Node** head, int target) {
if (*head == NULL || (*head)->data != target) {
printf("Element not found in the list.\n");
return;
}
Node* temp = *head;
*head = (*head)->next;
free(temp);
}
// 顺序查找
int search(Node* head, int target) {
Node* current = head;
while (current != NULL) {
if (current->data == target)
return 1; // 成功找到
current = current->next;
}
return 0; // 未找到
}
// 冒泡排序
void bubble_sort(Node** head) {
int len = 0, temp;
Node* current = *head;
while (current != NULL) {
len++;
current = current->next;
}
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - 1 - i; j++) {
if (*(head + j)->data > (*(head + j + 1))->data) {
temp = (*(head + j))->data;
*(head + j)->data = (*(head + j + 1))->data;
*(head + j + 1)->data = temp;
}
}
}
}
// 打印链表
void print_list(Node* head) {
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
}
int main() {
int arr[] = {1, 4, 5, 2, 3};
int size = sizeof(arr) / sizeof(arr[0]);
Node* list = create_list(arr, size);
// 插入0
insert_at_start(&list, 0);
printf("List after inserting 0: ");
print_list(list);
// 删除5
delete_node(&list, 5);
printf("List after deleting 5: ");
print_list(list);
// 排序并打印
bubble_sort(&list);
printf("Sorted list: ");
print_list(list);
// 查找3
if (search(list, 3)) {
printf("Element 3 found.\n");
} else {
printf("Element 3 not found.\n");
}
return 0;
}
```
这个C语言程序完成了顺序表的创建、插入0、删除5、排序以及查找3的操作。请注意,这个程序假设数组已经初始化好,并且需要一个适当大小的内存来容纳链表的节点。在实际应用中,你需要处理可能出现的边界条件和内存分配失败的情况。
阅读全文