生成实现顺序表的增删查找 打印的c语言代码
时间: 2024-11-20 08:43:47 浏览: 11
在C语言中,我们可以使用动态内存分配和指针来实现一个简单的顺序表(链表)。以下是基本的顺序表(动态数组)实现,包含插入、删除、查找和打印功能:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
// 初始化顺序表
Node* create_list() {
Node* head = (Node*)malloc(sizeof(Node));
head->data = 0;
head->next = NULL;
return head;
}
// 在头插入元素
void insert_at_head(Node** head, int item) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = item;
newNode->next = *head;
*head = newNode;
}
// 在尾插入元素
void insert_at_tail(Node** head, int item) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = item;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
return;
}
Node* last = *head;
while (last->next != NULL) {
last = last->next;
}
last->next = newNode;
}
// 删除头节点
void delete_from_head(Node** head) {
if (*head == NULL) {
printf("列表为空,无法删除。\n");
return;
}
Node* temp = *head;
*head = (*head)->next;
free(temp);
}
// 删除尾节点
void delete_from_tail(Node** head) {
if (*head == NULL) {
printf("列表为空,无法删除。\n");
return;
}
Node* current = *head;
Node* prev = NULL;
while (current->next != NULL) {
prev = current;
current = current->next;
}
if (prev == NULL) { // 只有一个节点
free(current);
*head = NULL;
} else {
prev->next = NULL;
free(current);
}
}
// 查找元素并返回其下标,若不存在返回-1
int search(Node* head, int item) {
Node* current = head;
int index = 0;
while (current != NULL) {
if (current->data == item) {
return index;
}
current = current->next;
index++;
}
return -1;
}
// 打印顺序表
void print_list(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
Node* head = create_list();
insert_at_head(&head, 5);
insert_at_tail(&head, 10);
insert_at_head(&head, 3);
print_list(head); // 打印:3 5 10
int position = search(head, 5);
if (position != -1) {
printf("找到了5的位置:%d\n", position);
} else {
printf("未找到5。\n");
}
delete_from_head(&head); // 删除第一个元素
print_list(head); // 打印:5 10
return 0;
}
```
阅读全文