C++实现单链表增删改查
时间: 2023-05-31 07:05:01 浏览: 132
单链表是一种常用的数据结构,它由一系列节点组成,每个节点包含一个数据元素和一个指向下一个节点的指针。单链表的操作包括增加节点、删除节点、修改节点和查找节点。下面是C语言实现单链表的增删改查示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 节点结构体
typedef struct node {
int data; // 数据元素
struct node* next; // 指向下一个节点的指针
} Node;
// 在单链表末尾增加节点
void addNode(Node** head, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (*head == NULL) {
*head = newNode;
} else {
Node* current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
// 在单链表指定位置插入节点
void insertNode(Node** head, int index, int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
if (index == 0) {
newNode->next = *head;
*head = newNode;
} else {
Node* current = *head;
for (int i = 0; i < index - 1 && current != NULL; i++) {
current = current->next;
}
if (current != NULL) {
newNode->next = current->next;
current->next = newNode;
} else {
printf("Index out of range\n");
}
}
}
// 在单链表指定位置删除节点
void deleteNode(Node** head, int index) {
if (*head == NULL) {
printf("List is empty\n");
return;
}
Node* current = *head;
Node* previous = NULL;
if (index == 0) {
*head = current->next;
free(current);
} else {
for (int i = 0; i < index && current != NULL; i++) {
previous = current;
current = current->next;
}
if (current != NULL) {
previous->next = current->next;
free(current);
} else {
printf("Index out of range\n");
}
}
}
// 修改单链表指定位置节点的值
void modifyNode(Node* head, int index, int data) {
if (head == NULL) {
printf("List is empty\n");
return;
}
Node* current = head;
for (int i = 0; i < index && current != NULL; i++) {
current = current->next;
}
if (current != NULL) {
current->data = data;
} else {
printf("Index out of range\n");
}
}
// 查找单链表指定位置节点的值
int searchNode(Node* head, int index) {
if (head == NULL) {
printf("List is empty\n");
return -1;
}
Node* current = head;
for (int i = 0; i < index && current != NULL; i++) {
current = current->next;
}
if (current != NULL) {
return current->data;
} else {
printf("Index out of range\n");
return -1;
}
}
// 打印单链表
void printList(Node* head) {
if (head == NULL) {
printf("List is empty\n");
return;
}
Node* current = head;
printf("List: ");
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
Node* head = NULL;
// 在单链表末尾增加节点
addNode(&head, 1);
addNode(&head, 2);
addNode(&head, 3);
printList(head);
// 在单链表指定位置插入节点
insertNode(&head, 1, 4);
insertNode(&head, 0, 5);
insertNode(&head, 6, 6);
printList(head);
// 在单链表指定位置删除节点
deleteNode(&head, 2);
deleteNode(&head, 0);
deleteNode(&head, 4);
printList(head);
// 修改单链表指定位置节点的值
modifyNode(head, 1, 7);
modifyNode(head, 3, 8);
modifyNode(head, 5, 9);
printList(head);
// 查找单链表指定位置节点的值
printf("Value at index 2: %d\n", searchNode(head, 2));
printf("Value at index 5: %d\n", searchNode(head, 5));
printf("Value at index 7: %d\n", searchNode(head, 7));
return 0;
}
```
阅读全文