www.pudn.com > Editor.rar > MyList.cpp
#include"Main.h" #include"MyList.h" templatebool MyList ::empty() { /* 返回bool型值,以判断队列是否为空 */ if(size==0)return true; return false; } template MyList ::MyList() { /* 构造函数,初始化队列 */ back=NULL; front=back; size=0; } template L MyList ::Front() { /* 如果队头为空,则返回NULL,否则返回队头 */ if(front==NULL){ //cout<<"Wrong!"; return NULL; } return front->data; } template L MyList ::Back() { /* 如果队尾为空,则返回NULL,否则返回队尾 */ if(back==NULL){ //cout<<"Wrong!"; return NULL; } return back->data; } template L MyList ::Position(int position) { /* 如果队列为空,则返回NULL,否则 如果position小于1,则返回队头,否则 如果position大于队列长度,则返回认尾,否则 返回position位置的结点值 */ if(size==0)return NULL; if(position<1)return front->data; if(position>size)return back->data; Node *temp=front; for(int i=0;i next; } return temp->data; } template void MyList ::Insert_front(L x) { /* 插入新结点到队头 如果原队列为空,则队尾和队头都指向新插入的结点 队列长度加1 */ Node *temp=new Node ; temp->data=x; temp->next=front; front=temp; if(size==0)back=front; size++; } template void MyList ::Insert_back(L x) { /* 插入新结点到队尾 如果原队列为空,则队尾和队头都指向新插入的结点 队列长度加1 */ Node *temp=new Node ; temp->data=x; temp->next=NULL; if(size==0){ back=temp; front=temp; size++; return; } back->next=temp; back=temp; size++; // cout<<"Insert success!"< void MyList ::Insert(int position,L x) { /* 如果position小于等于1,则插入新结点到队头,否则 如果position大于队列长度,则插入新结点到队尾,否则 插入新结点到position位置 如果原队列为空,则队尾和队头都指向新插入的结点 队列长度加1 */ Node *temp1,*temp2=front; if(position>size+1)position=size+1; if(position<=1){ temp1=new Node ; temp1->data=x; temp1->next=front; front=temp1; if(size==0)back=front; size++; return; } for(int i=0;i next; } temp1=new Node ; temp1->data=x; temp1->next=temp2->next; temp2->next=temp1; size++; } template int MyList ::Size() { /* 返回队列长度 */ return size; } template void MyList ::Print() { /* 打印队列元素 */ Node *temp=front; while(temp!=NULL){ cout< data< next; } } template bool MyList ::Remove_front() { /* 如果队列不为空,则移去队头,队列长度减1 */ if(size==0)return false; Node *temp=front; front=front->next; size--; delete temp; return true; } template bool MyList ::Remove_back() { /* 如果队列不为空,则移去队尾,队列长度减1 */ if(size==0)return false; if(size==1){ delete back; front=NULL; size--; return true; } Node *temp=back,*t=front; for(int i=0;i next; } back=t; back->next=NULL; delete temp; size--; return true; } template bool MyList ::Remove(int position) { /* 如果队列不为空且0 size)return false; if(position==1){ Node *te=front; front=front->next; delete te; size--; return true; } Node *temp,*t=front; for(int i=0;i next; } temp=t->next; t->next=t->next->next; delete temp; size--; return true; }