模块与群体数据

#include<iostream>
#include<cassert>
using namespace std;
template<typename T>
class OrderList{
public:
typedef struct _NODE{
T value;
struct _NODE* next;
}NODE,*PNODE;
OrderList():pHead(NULL),size(0){}
OrderList(const OrderList&ref)
:pHead(NULL),size(0){
PNODE pPos=ref.pHead;
while(pPos !=NULL){
this->InsertTail(pPos->value);
pPos=pPos->next;
}
}
OrderList& operator=(const OrderList&ref)
{
this->Clear();
PNODE pPos=ref.pHead;
while(pPos !=NULL){
this->InsertTail(pPos->value);
pPos=pPos->next;
}
return *this;
}
~OrderList(){
Clear();
}
bool isEmpty(){
return NULL==pHead ? true:false;
}
void insert(const T& value){
PNODE pNew=new NODE;
pNew->value=value;
PNODE p1=NULL;
PNODE p2=pHead;
while(p2 !=NULL&&p2->value<value){
p1=p2;
p2=p2->next;
}
if(NULL==p1){
pNew->next=pHead;
pHead=pNew;
}
else{
pNew->next=p1->next;
p1->next=pNew;
}
size +=1;
}
T DeleteHead(){
assert(!isEmpty());
T value;
PNODE pPos=pHead;
pHead=pPos->next;
value=pPos->value;
delete pPos;
pPos=NULL;
size-=1;
return value;
}
T DeleteTail()
{
if(0==size||1==size)
{
return DeleteHead();
}
else{
PNODE pPos=pHead;
while(pPos->next->value !=NULL)
{
pPos=pPos->next;
}
T value=pPos->next->value;
delete pPos->next;
pPos->next=NULL;
size-=1;
return value;
}
}
T &operator[](const int&index)const{
assert(index >=0 && index < size);
PNODE pPos=pHead;
for(int i=0;i<index;++i)
{
pPos=pPos->next;
}
return pPos->value;
}
void Clear();
PNODE GetHead()const{
return pHead;
}
protected:
PNODE pHead;
int size;
};
template<typename T>
void OrderList<T>::Clear(){
while(!isEmpty()){
DeleteHead();
}
}
template<typename T>
ostream&operator<<(ostream&os,const OderList<T>&list)
{
OrderList<T>::PNODE pPos=list.GetHead();
while(pPos !=NULL)
{
os<<pPos->value<<" ";
pPos=pPos->next;
}
return os;
}
int main()
{
OrderList<int>a;
a.insert(6);
a.insert(3);
a.insert(9);
a.insert(7);
a.insert(1);
OrderList<int>b;
b.insert(5);
b.insert(3);
b.insert(4);
b.insert(2);
b.insert(0);
while(!b.isEmpty())
{
int v=b.DeleteHead();
a.insert(v);
}
cout<<a<<endl;
cout<<b<<endl;
return 0;
}

posted @ 2023-05-04 20:36  不会JAVA的小袁  阅读(8)  评论(0编辑  收藏  举报