用c语言设计一个算法,在带头结点的非空单链表L中第一个最大值节点(最大值节点可能有多个)之前插入一个值为x的节点。
时间: 2023-10-20 14:07:38 浏览: 143
C语言写的带有头结点的链表
以下是用C语言设计的算法:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node, *LinkedList;
LinkedList createLinkedList(int arr[], int n) {
LinkedList head = (LinkedList) malloc(sizeof(Node));
head->next = NULL;
LinkedList p = head;
for (int i = 0; i < n; i++) {
LinkedList node = (LinkedList) malloc(sizeof(Node));
node->data = arr[i];
node->next = NULL;
p->next = node;
p = p->next;
}
return head;
}
void printLinkedList(LinkedList head) {
LinkedList p = head->next;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void insertNode(LinkedList L, int x) {
LinkedList p = L, q = L->next;
while (q != NULL && q->data < x) {
p = q;
q = q->next;
}
LinkedList node = (LinkedList) malloc(sizeof(Node));
node->data = x;
node->next = q;
p->next = node;
}
void insertBeforeMax(LinkedList L, int x) {
LinkedList p = L, q = L->next, maxNode = NULL;
int maxData = L->next->data;
while (q != NULL) {
if (q->data > maxData) {
maxData = q->data;
maxNode = q;
}
p = q;
q = q->next;
}
if (maxNode == NULL) {
printf("There is no max node in the linked list.\n");
} else {
insertNode(L, x);
}
}
int main() {
int arr[] = {1, 3, 5, 7, 9};
LinkedList L = createLinkedList(arr, 5);
printf("Original linked list: ");
printLinkedList(L);
insertBeforeMax(L, 6);
printf("After inserting 6 before the first max node: ");
printLinkedList(L);
return 0;
}
```
算法思路:
首先定义一个 `insertNode` 函数,用于在链表中插入一个值为 `x` 的节点,该函数会按照从小到大的顺序插入节点。
然后定义一个 `insertBeforeMax` 函数,用于在第一个最大值节点之前插入一个值为 `x` 的节点。该函数首先遍历链表找到最大值节点,然后在该节点之前调用 `insertNode` 函数插入节点。如果链表中没有最大值节点,则输出提示信息。
使用示例:
首先创建一个带头结点的链表,然后调用 `insertBeforeMax` 函数在第一个最大值节点之前插入一个节点,最后打印链表查看结果。
```c
int arr[] = {1, 3, 5, 7, 9};
LinkedList L = createLinkedList(arr, 5);
printf("Original linked list: ");
printLinkedList(L);
insertBeforeMax(L, 6);
printf("After inserting 6 before the first max node: ");
printLinkedList(L);
```
输出结果:
```
Original linked list: 1 3 5 7 9
After inserting 6 before the first max node: 1 3 5 6 7 9
```
阅读全文