编写一个C++程序,使用列表容器list顺序存储55、41、25、89、75这5个数据,将该数据序列进行排序后输出。
时间: 2023-06-08 17:03:54 浏览: 50
好的,你可以使用以下C语言代码实现:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
typedef struct ListNode {
int val;
struct ListNode* next;
} ListNode;
void addListNode(ListNode** head_ref, int val) {
ListNode* new_node = (ListNode*) malloc(sizeof(ListNode));
new_node->val = val;
new_node->next = NULL;
if (*head_ref == NULL) {
*head_ref = new_node;
} else {
ListNode* ptr = *head_ref;
while (ptr->next != NULL) {
ptr = ptr->next;
}
ptr->next = new_node;
}
}
void printList(ListNode* head) {
ListNode* ptr = head;
while (ptr != NULL) {
printf("%d ", ptr->val);
ptr = ptr->next;
}
printf("\n");
}
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
void bubbleSort(ListNode** head_ref) {
int n = 5;
bool swapped = true;
ListNode* end_ptr = NULL;
ListNode* curr = *head_ref;
while (swapped && n > 1) {
swapped = false;
curr = *head_ref;
for (int i = 0; i < n - 1; i++) {
if (curr->val > curr->next->val) {
swap(&(curr->val), &(curr->next->val));
swapped = true;
}
curr = curr->next;
}
n--;
end_ptr = curr;
}
}
int main() {
// create a list containing 55, 41, 25, 89 and 75
ListNode* head = NULL;
addListNode(&head, 55);
addListNode(&head, 41);
addListNode(&head, 25);
addListNode(&head, 89);
addListNode(&head, 75);
// sort the list using bubble sort
bubbleSort(&head);
// print the sorted list
printf("Sorted list: ");
printList(head);
return 0;
}
该程序使用链表实现了一个列表容器,调用 bubbleSort 函数对其中的数据进行了冒泡排序,并最终输出了排序后的结果。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.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://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)