和代码全部写一遍
时间: 2024-02-17 22:05:17 浏览: 13
好的,以下是完整的以单链表为存储结构的简单选择排序算法的代码实现:
```cpp
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* selectionSortList(ListNode* head) {
if (!head || !head->next) return head; // 特判链表为空或只有一个节点的情况
ListNode *dummy = new ListNode(0); // 定义一个虚拟头节点
dummy->next = head;
ListNode *cur = head;
while (cur->next) { // 循环遍历链表
ListNode *minNode = cur, *pre = dummy;
while (cur->next) { // 找到当前未排序部分的最小值节点以及其前一个节点
if (cur->next->val < minNode->val) {
minNode = cur->next;
pre = cur;
}
cur = cur->next;
}
if (minNode != cur) { // 如果最小值节点不是当前节点,交换它们的位置
pre->next = minNode->next;
minNode->next = cur->next;
cur->next = minNode;
}
cur = pre->next;
}
return dummy->next;
}
int main() {
ListNode* head = new ListNode(3);
head->next = new ListNode(1);
head->next->next = new ListNode(4);
head->next->next->next = new ListNode(2);
head = selectionSortList(head);
while (head) {
cout << head->val << " ";
head = head->next;
}
return 0;
}
```
输出结果为:1 2 3 4。
以上就是完整的以单链表为存储结构的简单选择排序算法的代码实现。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)