用c语言实现线性表增删改查main方法
时间: 2024-10-10 07:13:33 浏览: 49
在C语言中,我们通常会使用结构体来表示线性表,并提供函数来实现线性表的基本操作,如插入、删除、查找和修改元素。下面是一个简单的示例,展示了如何在一个动态数组中实现这些操作,这里假设我们的线性表存储整数。
```c
#include <stdio.h>
#include <stdlib.h>
// 定义线性表节点结构
typedef struct Node {
int data;
struct Node* next;
} Node;
// 动态创建节点并分配内存
Node* createNode(int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
return NULL;
}
newNode->data = value;
newNode->next = NULL;
return newNode;
}
// 插入节点到链表末尾
void insertNode(Node** head, int value) {
Node* newNode = createNode(value);
if (newNode != NULL) {
if (*head == NULL) {
*head = newNode;
} else {
Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
}
// 删除节点
void deleteNode(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 = current->next->next;
free(temp);
}
}
// 查找节点
Node* searchNode(Node* head, int value) {
Node* current = head;
while (current != NULL) {
if (current->data == value) {
return current;
}
current = current->next;
}
return NULL;
}
// 修改节点值
void updateNode(Node** head, int oldValue, int newValue) {
Node* node = searchNode(*head, oldValue);
if (node != NULL) {
node->data = newValue;
} else {
printf("Element not found in the list.\n");
}
}
int main() {
// 初始化头指针
Node* head = NULL;
// 示例操作
insertNode(&head, 10);
insertNode(&head, 20);
insertNode(&head, 30);
printf("Before updating: ");
printList(head); // 自定义函数用于打印列表
updateNode(&head, 20, 40);
printf("\nAfter updating: ");
printList(head); // 打印更新后的列表
// 删除节点
deleteNode(&head, 10);
printf("\nAfter deletion: ");
printList(head); // 打印删除后列表
return 0;
}
// 辅助函数,用于遍历并打印线性表
void printList(Node* head) {
while (head != NULL) {
printf("%d -> ", head->data);
head = head->next;
}
printf("NULL\n");
}
```
这个程序实现了基本的线性表操作,但是需要注意的是,这只是一个简化的例子,在实际项目中可能需要处理更多边界情况和错误处理。此外,`printList`函数需要用户自己实现。
阅读全文
相关推荐


















