实现单链表的冒泡排序
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
struct ListNode
{
ListNode* next;
int value;
};
bool List_insert(ListNode ** phead, int x, int i)
{
//空指针
if (phead == NULL)
{
return 0;
}
ListNode * pCurrent(NULL);
//头插入
if (i==1)
{
pCurrent = *phead;
ListNode * pNew = new ListNode;
pNew->value = x;
pNew->next = pCurrent;
*phead = pNew;
return 1;
}
//非头插入
pCurrent = *phead;
ListNode * pfront(NULL);
int k(1);
while (k < i && pCurrent != NULL)
{
pfront = pCurrent;
pCurrent = pCurrent->next;
k++;
}
if (k != i)
{
return 0;
}
ListNode * pNew = new ListNode;
pNew->value = x;
pNew->next = pCurrent;
pfront->next = pNew;
return 1;
}
void List_print(ListNode * phead)
{
while (phead!=NULL)
{
cout << phead->value;
phead = phead->next;
}
}
void List_Bubble_sort(ListNode** phead)
{
if (phead==NULL||*phead==NULL|| (*phead)->next==NULL )
{
return;
}
auto iter = *phead;
ListNode * stop = NULL;
for (; stop != *phead;)
{
for (; iter->next != stop; iter = iter->next)
{
if (iter->value > iter->next->value)
{
std::swap(iter->value, iter->next->value);
}
}
stop = iter;
iter = *phead;
}
}
int main()
{
ListNode * phead = NULL;
List_insert(&phead, 1, 1);
List_insert(&phead, 2, 1);
List_insert(&phead, 3, 1);
List_insert(&phead, 0, 2);
List_Bubble_sort(&phead);//冒泡排序
List_print(phead);
return 0;
}
更简单的实现:
void List_Bubble_sort(ListNode** phead)
{
ListNode * _tmp = *phead;
ListNode * _node= *phead;
int temp;
for (; _tmp->next;_tmp=_tmp->next)
{
for (_node = *phead; _node->next;_node= _node->next)
{
if (_node->value>_node->next->value)
{
std::swap(_node->value, _node->next->value);
}
}
}
}