c语言实现单链表基本操作
时间: 2023-09-20 08:14:30 浏览: 96
单链表是一种常见的数据结构,它由节点组成,每个节点包含一个数据元素和一个指向下一个节点的指针。下面是C语言实现单链表的基本操作的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构
struct Node {
int data;
struct Node* next;
};
// 创建新节点
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("内存分配失败!\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// 在链表末尾插入节点
void append(struct Node** head, int data) {
struct Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
return;
}
struct Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
// 在链表头部插入节点
void prepend(struct Node** head, int data) {
struct Node* newNode = createNode(data);
newNode->next = *head;
*head = newNode;
}
// 在指定位置插入节点
void insertAfter(struct Node* prevNode, int data) {
if (prevNode == NULL) {
printf("前一个节点不能为空!\n");
return;
}
struct Node* newNode = createNode(data);
newNode->next = prevNode->next;
prevNode->next = newNode;
}
// 删除指定数据的节点
void deleteNode(struct Node** head, int data) {
struct Node* temp = *head;
struct Node* prevNode = NULL;
if (temp != NULL && temp->data == data) {
*head = temp->next;
free(temp);
return;
}
while (temp != NULL && temp->data != data) {
prevNode = temp;
temp = temp->next;
}
if (temp == NULL) {
printf("未找到要删除的节点!\n");
return;
}
prevNode->next = temp->next;
free(temp);
}
// 打印链表
void printList(struct Node* head) {
struct Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
// 测试代码
int main() {
struct Node* head = NULL;
// 插入节点
append(&head,