以下是使用 C 语言实现的在带头结点的非空循环单链表中第一个最大结点之前插入一个值为 `x` 的结点的算法: ```c #include <stdio.h> #include <stdlib.h> // 定义链表节点结构体 typedef struct ListNode { int data; struct ListNode *next; } ListNode; // 创建新节点 ListNode *createNode(int data) { ListNode *newNode = (ListNode *)malloc(sizeof(ListNode)); if (newNode == NULL) { printf("内存分配失败\n"); return NULL; } newNode->data = data; newNode->next = NULL; return newNode; } // 插入节点 void insertBeforeMax(ListNode *head, int x) { ListNode *maxNode = head->next; ListNode *prevMax = head; ListNode *curr = head->next; ListNode *prev = head; // 找到最大节点和其前一个节点 while (curr!= head) { if (curr->data > maxNode->data) { maxNode = curr; prevMax = prev; } prev = curr; curr = curr->next; } // 创建新节点 ListNode *newNode = createNode(x); newNode->next = maxNode; prevMax->next = newNode; } // 打印链表 void printList(ListNode *head) { ListNode *curr = head->next; while (curr!= head) { printf("%d ", curr->data); curr = curr->next; } printf("\n"); } int main() { ListNode *head = createNode(0); // 头节点,数据域无意义 ListNode *node1 = createNode(10); ListNode *node2 = createNode(20); ListNode *node3 = createNode(15); head->next = node1; node1->next = node2; node2->next = node3; node3->next = head; // 形成循环链表 printf("原始链表: "); printList(head); int x = 30; insertBeforeMax(head, x); printf("插入后的链表: "); printList(head); // 释放链表内存 ListNode *temp; ListNode *curr = head; do { temp = curr; curr = curr->next; free(temp); } while (curr!= head); return 0; } ``` [2024-11-16 20:56:53 | AI写代码神器 | 629点数解答]