帮我用c++写一个实现链表功能的代码,要求实现链表的按值查找,指定节点输入,删除指定节点
时间: 2023-05-14 20:06:26 浏览: 67
好的,以下是实现链表功能的 C 代码:
```
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int value;
struct Node* next;
} Node;
// 创建新节点
Node* createNode(int value) {
Node* node = (Node*)malloc(sizeof(Node));
node->value = value;
node->next = NULL;
return node;
}
// 按值查找节点
Node* findNode(Node* head, int value) {
Node* cur = head;
while (cur != NULL) {
if (cur->value == value) {
return cur;
}
cur = cur->next;
}
return NULL;
}
// 插入节点
void insertNode(Node** head, Node* node) {
if (*head == NULL) {
*head = node;
} else {
Node* cur = *head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = node;
}
}
// 删除指定节点
void deleteNode(Node** head, Node* node) {
if (*head == node) {
*head = node->next;
free(node);
} else {
Node* cur = *head;
while (cur != NULL && cur->next != node) {
cur = cur->next;
}
if (cur != NULL) {
cur->next = node->next;
free(node);
}
}
}
// 打印链表
void printList(Node* head) {
Node* cur = head;
while (cur != NULL) {
printf("%d ", cur->value);
cur = cur->next;
}
printf("\n");
}
int main() {
Node* head = NULL;
// 插入节点
insertNode(&head, createNode(1));
insertNode(&head, createNode(2));
insertNode(&head, createNode(3));
insertNode(&head, createNode(4));
insertNode(&head, createNode(5));
// 打印链表
printf("链表内容:");
printList(head);
// 按值查找节点
Node* node = findNode(head, 3);
if (node != NULL) {
printf("查找到节点:%d\n", node->value);
} else {
printf("未找到节点\n");
}
// 删除指定节点
deleteNode(&head, node);
// 打印链表
printf("删除节点后的链表内容:");
printList(head);
return 0;
}
```
以上代码实现了链表的基本功能,包括创建新节点、按值查找节点、插入节点、删除指定节点和打印链表。如果您有其它问题,欢迎继续提问。