C语言3.4设计一个算法,在一个单链表中值为y的结点前面插入一个值为x的结点。即使值为x的新结点成为值为y的结点的前驱结点。
时间: 2023-10-30 14:08:14 浏览: 75
以下是C语言实现在单链表中插入新节点的算法:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义单链表结构体
typedef struct node {
int data;
struct node *next;
} Node, *LinkList;
// 初始化单链表
LinkList InitList() {
return NULL;
}
// 在单链表头部插入结点
LinkList InsertHead(LinkList head, int data) {
Node *newNode = (Node*) malloc(sizeof(Node));
newNode->data = data;
newNode->next = head;
head = newNode;
return head;
}
// 在单链表中插入新节点
void InsertNode(LinkList head, int x, int y) {
Node *p = head;
while (p->next != NULL && p->data != y) {
p = p->next;
}
if (p->data == y) {
Node *newNode = (Node*) malloc(sizeof(Node));
newNode->data = x;
newNode->next = p->next;
p->next = newNode;
} else {
printf("The node with the value of y is not found!");
}
}
// 打印单链表
void PrintList(LinkList head) {
Node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
}
int main() {
// 初始化单链表
LinkList head = InitList();
// 在单链表头部插入结点
head = InsertHead(head, 1);
head = InsertHead(head, 2);
head = InsertHead(head, 3);
head = InsertHead(head, 4);
head = InsertHead(head, 5);
// 在单链表中插入新节点
InsertNode(head, 6, 3);
// 打印单链表
PrintList(head);
return 0;
}
```
输出结果为:
```
5 4 3 6 2 1
```
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)