第一个头文件SNode.h
#ifndef SNODE_H_
#define SNODE_H_
#include "stddef.h"
#include <iostream>
using namespace std;
struct SNode
{
int data;
SNode *pNext;
SNode *pPre;
};
#endif
第二个头文件CList.h
#ifndef LIST_H_
#define LIST_H_
#include "SNode.h"
class CList
{
private:
SNode *chead;
int count;
public:
CList():chead(0), count(0) {}
virtual ~CList() { freeall(); };
void CAddhead(int x);
void CAddtail(int x);
void print();
void printnum();
void freeall();
void sort();
void remove(int x);
};
void CList::CAddhead(int x)
{
SNode *pnew = new SNode;
pnew ->data = x;
pnew ->pPre = NULL;
pnew ->pNext = NULL;
if(chead)
{
SNode *temp = chead;
while(temp ->pPre)
temp = temp ->pPre;
temp ->pPre = pnew;
pnew ->pNext = temp;
}
chead = pnew;
count++;
}
void CList::CAddtail(int x)
{
SNode *pnew = new SNode;
pnew ->data = x;
pnew ->pPre = NULL;
pnew ->pNext = NULL;
if(!chead)
chead = pnew;
else
{
SNode *temp = chead;
while(temp ->pNext)
temp = temp ->pNext;
temp ->pNext = pnew;
pnew ->pPre = temp;
}
count++;
}
void CList::print()
{
SNode *temp = chead;
while(temp)
{
cout << temp ->data <<endl;
temp = temp ->pNext;
}
}
void CList::printnum()
{
cout << "The number of nodes is:" << count <<endl;
}
void CList::freeall()
{
SNode *p1;
while(chead)
{
p1 = chead;
chead = chead ->pNext;
delete p1;
}
}
void CList::sort()
{
SNode *temp;
SNode *p = chead;
int min = 0;
while(p ->pNext)
{
min = p ->data;
temp = p;
while(temp)
{
if(temp ->data < min)
{
min = temp ->data;
int m;
m = temp ->data;
temp ->data = p ->data;
p ->data = m;
}
temp = temp ->pNext;
}
p = p ->pNext;
}
}
void CList::remove(int x)
{
SNode *temp = chead;
while(temp)
{
if( temp ->data == x)
{
SNode *p1 = temp;
if( temp ->pNext && temp ->pPre)
{
temp ->pPre ->pNext = temp ->pNext;
temp ->pNext ->pPre = temp ->pPre;
temp = temp ->pNext;
}
else if( !temp ->pPre )
{
temp = temp ->pNext;
temp ->pPre = NULL;
chead = temp;
}
else if( !temp ->pNext )
{
temp ->pPre ->pNext = NULL;
temp = NULL;
}
delete p1;
count--;
continue;
}
temp = temp ->pNext;
}
}
#endif