下面是使用C语言实现链表的插入排序算法的示例代码,其中包含了注释来说明每个函数关键步骤的作用。
- #include <stdio.h>
- #include <stdlib.h>
- // 链表节点结构
- struct ListNode {
- int val;
- struct ListNode* next;
- };
- // 创建新节点
- struct ListNode* createNode(int val) {
- struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
- newNode->val = val;
- newNode->next = NULL;
- return newNode;
- }
- // 插入排序算法
- void insertionSortList(struct ListNode** head) {
- // 如果链表为空或只有一个节点,则无需排序
- if (*head == NULL || (*head)->next == NULL) {
- return;
- }
-
- struct ListNode* sorted = NULL; // 已排好序部分的头节点
- struct ListNode* curr = *head; // 当前待排序节点
-
- while (curr != NULL) {
- struct ListNode* nextNode = curr->next; // 下一个待排序节点
-
- // 在已排序部分找到合适的位置插入当前节点
- if (sorted == NULL || curr->val < sorted->val) {
- curr->next = sorted;
- sorted = curr;
- } else {
- struct ListNode* temp = sorted;
-
- while (temp->next != NULL && curr->val >= temp->next->val) {
- temp = temp->next;
- }
-
- curr->next = temp->next;
- temp->next = curr;
- }
-
- curr = nextNode; // 处理下一个待排序节点
- }
-
- *head = sorted; // 更新链表头节点为已排序部分的头节点
- }
- // 打印链表
- void printList(struct ListNode* head) {
- struct ListNode* curr = head;
-
- while (curr != NULL) {
- printf("%d ", curr->val);
- curr = curr->next;
- }
-
- printf("\n");
- }
- int main() {
- // 创建链表: 3 -> 1 -> 4 -> 2
- struct ListNode* head = createNode(3);
- head->next = createNode(1);
- head->next->next = createNode(4);
- head->next->next->next = createNode(2);
-
- printf("原始链表: ");
- printList(head);
-
- // 使用插入排序算法进行排序
- insertionSortList(&head);
-
- printf("排序后链表: ");
- printList(head);
-
- return 0;
- }
复制代码
这段代码使用了简单的插入排序算法来对链表进行排序。首先创建了一个新节点的函数 createNode(),然后定义了插入排序算法函数 insertionSortList() 和打印链表函数 printList()。
在 insertionSortList() 函数中,通过迭代遍历链表,将每个节点插入到已排好序的部分中的正确位置。这里使用了两个指针 sorted 和 curr,sorted 指向已排好序部分的头节点,curr 指向当前待排序节点。根据当前节点的值与已排序部分的节点值的大小关系,选择合适的位置进行插入操作。
最后在 main() 函数中创建一个示例链表,调用插入排序算法函数对链表进行排序,并使用打印链表函数将结果输出。