#include<iostream>
using namespace std;
class CList
{
private:
struct Node
{
int nValue;
Node* pNext;
};
Node* m_pHead; //链表头尾,长度
Node* m_pEnd;
int m_nLength;
public:
CList() //创建空链表
{
m_pHead = NULL;
m_pEnd = NULL;
m_nLength = 0;
}
CList(int nCount) //创建有nCount个结点的链表
{
// 初始化成员变量
m_pHead = NULL;
m_pEnd = NULL;
m_nLength = 0;
for (int i = 0;i < nCount;i++)
{
Push_Back(0);
}
}
~CList()
{
while(m_pHead)
Pop_Front();
}
public:
void Push_Back(int nValue) //在链表上添加一个数
{
//创建一个结点,把值装进去
Node* node = new Node;
node->nValue = nValue;
node->pNext = NULL;
//把这个结点放到链表的尾部
if(!m_pHead) //如果现在没有链表的时候
{
m_pHead = node;
m_pEnd = node;
}
else //链表有结点的时候
{
m_pEnd->pNext = node;
m_pEnd = node;
}
m_nLength++;
}
void Pop_Front() //删除一个链表结点
{
//判断链表有没有结点
if(m_pHead == NULL)
return;
//只有一个结点的时候
if(m_pHead == m_pEnd)
{
delete m_pHead;
m_pHead = NULL;
m_pEnd = NULL;
m_nLength = 0;
return ;
}
//有多个结点的时候
Node *pDel = m_pHead;
m_pHead = m_pHead->pNext;
delete pDel;
pDel = NULL;
m_nLength--;
}
void Show() //测试函数
{
Node* pTemp = m_pHead;
while (pTemp)
{
cout << pTemp->nValue <<" ";
pTemp = pTemp->pNext;
}
cout << "nLength:"<<m_nLength<<endl;
}
};
int main()
{
CList lst1; //创建lst1对象,调用第一个构造函数,其中有一个初始结点
lst1.Show();
CList lst2(10); //创建lst2对象,调用第二个构造函数,传入参数,参数为创建结点的个数
lst2.Show();
lst1.Push_Back(1);
lst1.Show();
lst2.Pop_Front();
lst2.Show();
system("pause");
return 0;
}
运行结果: