C语言链表排序算法优化与注释

简介

链表是一种常见的数据结构,排序是常见的操作之一。本文将介绍如何使用冒泡排序算法对C语言链表进行排序,并对代码进行优化和添加详细注释,帮助你理解链表排序的实现过程。

代码实现c#include <stdio.h>#include <stdlib.h>

// 定义链表节点结构struct Node { int data; struct Node* next;};

// 在链表末尾插入新节点void insertAtEnd(struct Node** head, int data) { // 创建新节点 struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->data = data; newNode->next = NULL;

// 如果链表为空,将新节点设为头节点 if (*head == NULL) { *head = newNode; return; }

// 找到链表末尾节点 struct Node* temp = *head; while (temp->next != NULL) { temp = temp->next; }

// 在末尾插入新节点 temp->next = newNode;}

// 交换两个节点的数据void swap(struct Node* a, struct Node* b) { int temp = a->data; a->data = b->data; b->data = temp;}

// 使用冒泡排序对链表进行排序void bubbleSort(struct Node* head) { if (head == NULL || head->next == NULL) { return; }

int swapped; struct Node* ptr1; struct Node* lptr = NULL;

do { swapped = 0; ptr1 = head;

while (ptr1->next != lptr) {      if (ptr1->data > ptr1->next->data) {        swap(ptr1, ptr1->next);        swapped = 1;      }      ptr1 = ptr1->next;    }    lptr = ptr1;  } while (swapped);}

// 打印链表void printList(struct Node* node) { while (node != NULL) { printf('%d ', node->data); node = node->next; } printf(' ');}

int main() { struct Node* head = NULL;

// 向链表中插入节点 insertAtEnd(&head, 5); insertAtEnd(&head, 3); insertAtEnd(&head, 8); insertAtEnd(&head, 1); insertAtEnd(&head, 6);

printf('原始链表: '); printList(head);

// 对链表进行排序 bubbleSort(head);

printf('排序后的链表: '); printList(head);

// 释放链表的内存 struct Node* current = head; while (current != NULL) { struct Node* next = current->next; free(current); current = next; }

return 0;}

代码解释

  1. 定义链表节点结构: struct Node 结构体定义了链表的节点,包含数据域 data 和指向下一个节点的指针 next。2. insertAtEnd 函数: 该函数用于在链表末尾插入新的节点。3. swap 函数: 该函数用于交换两个节点的数据。4. bubbleSort 函数: 该函数实现了冒泡排序算法,对链表进行排序。5. printList 函数: 该函数用于打印链表中的所有节点数据。6. main 函数: 主函数中创建了一个链表,并演示了如何使用上述函数进行插入节点、排序和打印操作。

优化

  • 内存释放:main 函数结束前,使用循环遍历链表并释放每个节点的内存,防止内存泄漏。

总结

本文介绍了如何使用冒泡排序算法对C语言链表进行排序,并对代码进行了优化和添加了详细注释。了解链表排序的实现方法可以帮助你更好地理解链表这种数据结构,并在实际编程中灵活运用。

C语言链表排序算法优化与注释

原文地址: http://www.cveoy.top/t/topic/uhk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录