大家好,今天继续模板实战编程,我们今天的目标是用模板写一个针对链表的冒泡排序算法,具体如例1所示。
例1 冒泡排序-链表
ListBubbleSort.hpp的内容:
#ifndef _LIST_BUBBLE_SORT_H_
#define _LIST_BUBBLE_SORT_H_
#include <iostream>
using namespace std;
template<typename T>
struct Node
{
T m_Data;
Node * m_pNext;
};
template<typename T>
bool BubbleSort(Node<T> * & pHead)
{
Node<T> * pCurNode = NULL;
Node<T> * pTemp = NULL;
Node<T> * pNext = NULL;
T tTemp;
bool bChange = false;
if (!pHead)
return false;
pCurNode = pHead;
while (pCurNode)
{
pTemp = pHead;
pNext = pTemp->m_pNext;
bChange = false;
while (pTemp && pNext)
{
if (pTemp->m_Data > pNext->m_Data)
{
tTemp = pTemp->m_Data;
pTemp->m_Data = pNext->m_Data;
pNext->m_Data = tTemp;
bChange = true;
}
pTemp = pTemp->m_pNext;
pNext = pTemp->m_pNext;
}
if (!bChange)
break;
pCurNode = pCurNode->m_pNext;
}
return true;
}
#endif
main.cpp的内容:
#include "ListBubbleSort.hpp"
#include <time.h>
void main()
{
int i = 0;
Node<int> * pInt = NULL;
Node<int> * pNewNode = NULL;
Node<int> * pCurNode = NULL;
srand(time(NULL));
for (i = 0; i < 10; i++)
{
pNewNode = new Node<int>;
if (pNewNode == NULL)
{
while (pInt)
{
pCurNode = pInt;
pInt = pInt->m_pNext;
delete pCurNode;
}
pInt = NULL;
return;
}
pNewNode->m_Data = rand() % 100;
pNewNode->m_pNext = pInt;
pInt = pNewNode;
}
cout << "排序前:" << endl;
pCurNode = pInt;
while (pCurNode)
{
cout << pCurNode->m_Data << '\t';
pCurNode = pCurNode->m_pNext;
}
cout << endl;
if (BubbleSort<int>(pInt) == false)
{
cout << "排序失败." << endl;
}
else
{
cout << "排序成功." << endl;
}
cout << "排序后:" << endl;
pCurNode = pInt;
while (pCurNode)
{
cout << pCurNode->m_Data << '\t';
pCurNode = pCurNode->m_pNext;
}
cout << endl;
while (pInt)
{
pCurNode = pInt;
pInt = pInt->m_pNext;
delete pCurNode;
}
pInt = NULL;
_CrtDumpMemoryLeaks();
system("pause");
return;
}
运行效果如图1所示:
图1 运行效果
今天,我们一起实现了链表的冒泡排序,希望大家回去再实践一下,加深体会。