今天,我们共同写一个针对链表的插入排序算法,为了加深对模板的体会,这里使用函数模板机制,具体如例1所示。
例1 插入排序-链表
ListInsertSort.hpp内容:
#ifndef _LIST_INSERT_SORT_H_ #define _LIST_INSERT_SORT_H_ #include<iostream> using namespace std; template<typename T> struct Node { T m_Data; Node * m_pNext; }; //插入排序 template<typename T> bool InsertSort(Node<T> * & pHead) { Node<T> * pCurNode = NULL; Node<T> * pPrevNode = NULL; Node<T> * pPrevNode2 = NULL; Node<T> * pNextNode = NULL; Node<T> * pTemp = NULL; T tTemp; if (pHead == NULL) return false; if (pHead->m_pNext == NULL) return true; for (pPrevNode = pHead,pCurNode = pHead->m_pNext; pCurNode;) { pNextNode = pCurNode->m_pNext; tTemp = pCurNode->m_Data; for (pTemp = pHead, pPrevNode2 = NULL; (pTemp != pCurNode) && (pTemp->m_Data <= tTemp); pPrevNode2 = pTemp, pTemp = pTemp->m_pNext); if (pTemp != pCurNode) { if (pPrevNode2 == NULL) { //头结点 pPrevNode->m_pNext = pCurNode->m_pNext; pCurNode->m_pNext = pTemp; pHead = pCurNode; pCurNode = pPrevNode->m_pNext; continue; } //中间插入 pPrevNode2->m_pNext = pCurNode; pCurNode->m_pNext = pTemp; pPrevNode->m_pNext = pNextNode; pCurNode = pNextNode; continue; } pPrevNode = pCurNode; pCurNode = pCurNode->m_pNext; } return true; } #endifmain.cpp
#define CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> #include "ListInsertSort.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 << ' '; pCurNode = pCurNode->m_pNext; } cout << endl; if (InsertSort<int>(pInt) == false) { cout << "排序失败." << endl; } else { cout << "排序成功." << endl; } cout << "排序后:" << endl; pCurNode = pInt; while (pCurNode) { cout << pCurNode->m_Data << ' '; pCurNode = pCurNode->m_pNext; } cout << endl; while (pInt) { pCurNode = pInt; pInt = pInt->m_pNext; delete pCurNode; } pInt = NULL; _CrtDumpMemoryLeaks(); system("pause"); return; }
运行效果:
图1 运行效果
今天我们共同完成了插入排序,希望大家多实践,加深体会。