C++单链表选择排序

这篇博客介绍了如何使用C++编程实现链表的选择排序。通过定义链表节点结构,创建了一个选择排序函数ListSelectSort,该函数遍历链表,找到最小值并将其放到链表头部。同时提供了一个getSmallestNode函数来获取链表中最小值的节点。最后,通过print函数打印排序后的链表。
#include <iostream>


struct Node {
int value;
Node *next;


Node(int data) : value(data), next(nullptr) {};
};


Node * ListSelectSort(Node * head);
Node * getSmallestNode(Node * head);
void print(Node * head);


int main()
{
Node n1(15);
Node n2(3);
Node n3(8);
Node n4(11);
Node n5(2);
Node n6(1);
n1.next = &n2;
n2.next = &n3;
n3.next = &n4;
n4.next = &n5;
n5.next = &n6;


print(ListSelectSort(&n1));




system("pause");
return 0;
}


Node * ListSelectSort(Node * head)
{
Node * tail = nullptr;
Node * cur = head;
Node * smallpre = nullptr;
Node * small = nullptr;


while (cur != nullptr)
{
small = cur;
smallpre = getSmallestNode(cur);
if (smallpre != nullptr)
{
small = smallpre->next;
smallpre->next = small->next;
}
cur = cur == small ? cur->next : cur;


if (tail == nullptr)
{
head = small;
}
else
{
tail->next = small;
}
tail = small;
}
return head;
}


Node * getSmallestNode(Node * head)
{
Node * smallpre = nullptr;
Node * pre = head;
Node * small = head;
Node * cur = head->next;


while (cur != nullptr)
{
if (cur->value < small->value)
{
smallpre = pre;
small = cur;
}
pre = cur;
cur = cur->next;
}


return smallpre;
}


void print(Node * head)
{
while (head != nullptr)
{
std::cout << head->value << std::endl;
head = head->next;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值