在一个单链表中值为y的结点前插入一个值为x的结点即使值为x的新结点成为值为y的结点的前驱结点。用c语言来完成一段完整的代码。要求有输入输出
#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;
原文地址: https://www.cveoy.top/t/topic/fblx 著作权归作者所有。请勿转载和采集!