//单链表冒泡排序
//需要三个指针cur,next,tail,tail指向每次冒泡冒到的终止位置
//第一趟next为空停止,把cur给tail,再让cur和next到前面去再开始冒泡
void BubbleSort(Node* pHead)
{
Node* tail = NULL;
if (pHead == NULL || pHead->next == NULL)//头指针为空,或者它的下一个节点为空,不用
冒泡了
{
return;
}
while (tail != pHead)//冒泡停止的位置不到头结点就继续冒
{
Node* cur = pHead, *next = cur->next;
while (next != tail)
{
if (cur->data > next->data)
{
DataType tmp = cur->data;
cur->data = next->data;
next->data = tmp;
}
cur = cur->next;
next = next->next;
}
tail = cur;
}
}
void TestTopic1()
{
Node* list = NULL;
Node* tail;
PushBack(&list, 6);
PushBack(&list, 2);
PushBack(&list, 1);
PushBack(&list, 8);
PushBack(&list, 5);
PrintList(list);
BubbleSort(list);
PrintList(list);
}
输出结果:
62185
12568
//需要三个指针cur,next,tail,tail指向每次冒泡冒到的终止位置
//第一趟next为空停止,把cur给tail,再让cur和next到前面去再开始冒泡
void BubbleSort(Node* pHead)
{
Node* tail = NULL;
if (pHead == NULL || pHead->next == NULL)//头指针为空,或者它的下一个节点为空,不用
冒泡了
{
return;
}
while (tail != pHead)//冒泡停止的位置不到头结点就继续冒
{
Node* cur = pHead, *next = cur->next;
while (next != tail)
{
if (cur->data > next->data)
{
DataType tmp = cur->data;
cur->data = next->data;
next->data = tmp;
}
cur = cur->next;
next = next->next;
}
tail = cur;
}
}
void TestTopic1()
{
Node* list = NULL;
Node* tail;
PushBack(&list, 6);
PushBack(&list, 2);
PushBack(&list, 1);
PushBack(&list, 8);
PushBack(&list, 5);
PrintList(list);
BubbleSort(list);
PrintList(list);
}
输出结果:
62185
12568