Linu c++ 簡單實現連結串列類模板
阿新 • • 發佈:2019-01-24
之前在C語言裡面有實現連結串列,現在用c++簡單的實現連結串列類,只實現了插入節點和排序,我先開個好頭,其餘的程式碼基本上和C語言裡面的程式碼差不多,直接上程式碼咯;
#include <iostream>
#include <cstdio>
using namespace std;
template<class Type>
class CList
{private:
class CNode
{
public:
CNode* m_pNext;
Type m_Data;
CNode()
{
m_pNext = NULL;
}
};
CNode* m_pHead;
int m_NodeSum;
public:
CList()
{
m_pHead = NULL;
m_NodeSum = 0;
}
void PushBack(Type Data)
{
CNode* pNewNode = new CNode();
pNewNode->m_Data = Data;
if(m_NodeSum == 0)
m_pHead = pNewNode;
else
{
CNode* pTmp = m_pHead;
for(int i = 1;i < m_NodeSum;i++)
pTmp = pTmp->m_pNext;
pTmp->m_pNext = pNewNode;
}
m_NodeSum++;
}
void NodeSort()
{
CNode* pSort = m_pHead;
CNode* pTmp = NULL;
Type tTmp;
while(pSort != NULL)
{
pTmp = pSort->m_pNext;
while(pTmp != NULL)
{
if(pTmp->m_Data < pSort->m_pNext->m_Data)
{
tTmp = pSort->m_pNext->m_Data;
pSort->m_pNext->m_Data = pTmp->m_Data;
pTmp->m_Data = tTmp;
}
pTmp = pTmp->m_pNext;
}
pSort = pSort->m_pNext;
}
}
void NodeSize()
{
cout<<m_NodeSum<<endl;
}
void ShowAll()
{
if(m_NodeSum > 0)
{
CNode* pTmp = m_pHead;
while(pTmp != NULL)
{
cout<<pTmp->m_Data<<"\t";
pTmp = pTmp->m_pNext;
}
cout<<endl;
}
}
~CList()
{
if(m_NodeSum > 0)
{
CNode* pDelete = m_pHead;
CNode* pTmp = NULL;
while(pDelete != NULL)
{
pTmp = pDelete->m_pNext;
delete pDelete;
pDelete = pTmp;
}
m_NodeSum = 0;
pDelete = NULL;
pTmp = NULL;
}
m_pHead = NULL;
}
};
int main()
{
CList<int> List;
List.PushBack(11);
List.PushBack(20);
List.PushBack(13);
List.PushBack(14);
List.PushBack(15);
List.NodeSize();
List.ShowAll();
List.NodeSort();
List.ShowAll();
CList<float> Listb;
Listb.PushBack(11.4);
Listb.PushBack(15.4);
Listb.PushBack(12.4);
Listb.PushBack(18.4);
Listb.ShowAll();
return 0;
}
是不是覺得,用C++來實現連結串列又有不一樣的感覺呢,希望能幫到你。。。