链表类C++

#include<iostream>
using namespace std;

class CList
{
private:
 struct Node
 {
  int nValue;
  Node* pNext;
 };
 Node* pHead;
 Node* pEnd;
 int nLength;
public:
 CList()
 {
  pHead = NULL;
  pEnd = NULL;
  nLength = 0;
 }
 CList(int nCount,int nValue=0)
 {
  pHead = NULL;
  pEnd = NULL;
  nLength = 0;

  for(int i=0;i<nCount;i++)
   Push_Back(nValue);
 }
 ~CList()
 {
  while(pHead)
   Pop();

  pHead = NULL;
  pEnd = NULL;
  nLength = 0;
 }
 void Push_Back(int nValue)
 {
  Node* temp = new Node;
  temp->nValue = nValue;
  temp->pNext = NULL;

  nLength++;

  if(!pHead)
   pHead=temp;
  else
   pEnd->pNext = temp;
  pEnd = temp;
 }
 void Pop()
 {
  Node* pDel = pHead;
  
  if(pHead == pEnd)
  {
   delete pDel;
   pHead = NULL;
   pEnd = NULL;

   nLength = 0;
   return ;
  }
  else
  {
   pHead = pHead->pNext;
   delete pDel;
   pDel = NULL;
   nLength--;
  }
 }
 void Show()
 {
  Node* temp = pHead;
  while (temp)
  {
   cout << temp->nValue << " ";
   temp = temp->pNext;
  }
  cout << nLength << endl;
 }
};

int main()
{
  
 CList lst1;

 lst1.Show();

 CList lst2(10);

 lst2.Show();

 CList lst3(10,123);

 lst3.Show();


 lst1.Push_Back(456);

 lst3.Pop();

 lst1.Show();
 lst3.Show();


 system("pause");
 return 0;
}

你可能感兴趣的:(链表类C++)