用c语言写出单链表的增删查合并逆置
时间: 2024-10-14 11:15:10 浏览: 37
在C语言中,单链表是一种常见的数据结构,用于存储一系列动态大小的数据元素。以下是关于单链表的一些基本操作:
**创建链表:**
```c
typedef struct Node {
int data;
struct Node* next;
} Node;
// 创建一个新的节点并添加到链表尾部
Node* createNode(int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = NULL;
return newNode;
}
```
**插入操作(增):**
```c
void insertNode(Node** head, int value) {
Node* newNode = createNode(value);
if (*head == NULL) {
*head = newNode;
} else {
Node* temp = *head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}
```
**删除操作(删):**
```c
void deleteNode(Node** head, int value) {
if (*head == NULL) {
return;
}
if ((*head)->data == value) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
return;
}
Node* prev = *head;
Node* current = *head->next;
while (current != NULL && current->data != value) {
prev = current;
current = current->next;
}
if (current != NULL) {
prev->next = current->next;
free(current);
}
}
```
**查找操作(查):**
```c
int searchNode(Node* head, int value) {
Node* temp = head;
while (temp != NULL) {
if (temp->data == value) {
return 1; // 数据存在,返回1
}
temp = temp->next;
}
return 0; // 数据不存在,返回0
}
```
**合并两个有序链表:**
```c
Node* mergeSortedLists(Node* list1, Node* list2) {
if (list1 == NULL) {
return list2;
}
if (list2 == NULL) {
return list1;
}
if (list1->data <= list2->data) {
list1->next = mergeSortedLists(list1->next, list2);
return list1;
} else {
list2->next = mergeSortedLists(list1, list2->next);
return list2;
}
}
```
**反转链表:**
```c
void reverseList(Node** head) {
Node* prev = NULL;
Node* current = *head;
Node* nextTemp = NULL;
while (current != NULL) {
nextTemp = current->next;
current->next = prev;
prev = current;
current = nextTemp;
}
*head = prev;
}
```
**
阅读全文