#include <stdio.h> #include <stdlib.h>

// 定义链表结点 struct node { int data; struct node *next; };

// 在值为y的结点前插入值为x的新结点 void insert_node(struct node *head, int x, int y) { struct node *p, q; p = head; q = (struct node)malloc(sizeof(struct node)); q->data = x; while(p->next != NULL) { if(p->next->data == y) { q->next = p->next; p->next = q; return; } p = p->next; } printf('插入失败,未找到值为%d的结点\n', y); }

// 创建链表 struct node *create_list(int n) { struct node *head, p, q; head = (struct node)malloc(sizeof(struct node)); head->next = NULL; p = head; for(int i=0; i<n; i++) { q = (struct node)malloc(sizeof(struct node)); printf('请输入第%d个结点的值:', i+1); scanf('%d', &(q->data)); p->next = q; p = q; } p->next = NULL; return head; }

// 输出链表 void print_list(struct node *head) { struct node *p; p = head->next; while(p != NULL) { printf('%d ', p->data); p = p->next; } printf('\n'); }

int main() { int n, x, y; struct node *head; printf('请输入链表的长度:'); scanf('%d', &n); head = create_list(n); printf('原始链表为:'); print_list(head); printf('请输入要插入的值x和要插入在哪个值y的结点前:'); scanf('%d%d', &x, &y); insert_node(head, x, y); printf('插入后的链表为:'); print_list(head); return 0; }

C语言单链表插入结点:在值为y的结点前插入值为x的结点

原文地址: https://www.cveoy.top/t/topic/n33f 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录