头文件1 SNode.h
#ifndef SNODE_H_
#define SNODE_H_
#include "stddef.h"
#include <iostream>
using namespace std;
struct SNode
{
int data;
SNode *pNext;
};
#endif
头文件2 List.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 ->pNext = chead;
chead = pnew;
count++;
}
void CList::CAddtail(int x)
{
SNode *pnew = new SNode;
pnew ->data = x;
pnew ->pNext = NULL;
if(!chead)
chead = pnew;
else
{
SNode *temp = chead;
while(temp ->pNext)
temp = temp ->pNext;
temp ->pNext = pnew;
}
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;
if(chead ->data == x)
{
chead = chead ->pNext;
delete temp;
}
else while(temp ->pNext)
{
if( temp ->pNext ->data == x)
{
SNode *p1 = temp ->pNext;
if( temp ->pNext ->pNext)
temp ->pNext = temp ->pNext ->pNext;
else temp ->pNext = NULL;
delete p1;
count--;
continue;
}
temp = temp ->pNext;
}
}
#endif