单向链表中,如何在给定节点前快速插入一个节点?

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个示例程序,实现了根据给定整数在单向链表查找并插入节点的功能: ```c #include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; }; struct Node* insert(struct Node* head, int target, int value) { struct Node* current = head; while (current != NULL) { if (current->data == target) { // 找到目标节点,创建节点插入链表 struct Node* new_node = malloc(sizeof(struct Node)); new_node->data = value; new_node->next = current->next; current->next = new_node; return head; } current = current->next; } // 没有找到目标节点,打印原链表 current = head; while (current != NULL) { printf("%d ", current->data); current = current->next; } printf("\n"); return head; } int main() { // 创建包含 n 个节点单向链表 int n; printf("请输入链表节点的个数 n:"); scanf("%d", &n); struct Node* head = NULL; struct Node* tail = NULL; for (int i = 0; i < n; i++) { int value; printf("请输入节点 %d 的值:", i + 1); scanf("%d", &value); struct Node* new_node = malloc(sizeof(struct Node)); new_node->data = value; new_node->next = NULL; if (head == NULL) { head = new_node; tail = new_node; } else { tail->next = new_node; tail = new_node; } } // 根据给定整数查找并插入节点 int target, value; printf("请输入要查找的整数:"); scanf("%d", &target); printf("请输入要插入整数:"); scanf("%d", &value); head = insert(head, target, value); // 释放链表内存 struct Node* current = head; while (current != NULL) { struct Node* temp = current; current = current->next; free(temp); } return 0; } ``` 在这个示例程序,我们定义了一个 `insert` 函数,接收链表头指针、目标值和值作为输入,如果找到目标节点就在其后面插入节点,并返回链表的头指针;如果没有找到目标节点,就打印原链表并返回原链表的头指针。在 `main` 函数,我们首先创建一个包含 n 个节点单向链表,然后根据给定整数查找并插入节点。最后,我们释放了链表的内存。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值