您的位置:首页 > 其它

模板实现双向链表

2016-03-31 00:13 369 查看
/************************************

WZ ASUST   2016

模板实现双向链表

************************************/

#include"sts.h"
template <class T>
struct node
{
public:node(const T &d):next(NULL),prve(NULL),data(d){}
T data;
node<T> *next;
node<T> *prve;
};
template <class T>
class dlist
{
private: node<T>* head;node<T>* tail;
public:
dlist():head(NULL),tail(NULL){};
~dlist(){node<T>*cur=head;while(cur){node<T>*del=cur;cur=cur->next;delete del;}}
void print(){node<T>*cur=head;while(cur){cout<<cur->data<< " ";cur=cur->next;}cout<<"ok"<<endl;}
// void  dlist(const dlist<T>&dl){}//while not error
dlist & operator=(const dlist <T> & dl)
{
if(this!=&dl)
{
head=dl.head;
tail=dl.tail;
node<T>*dlcur=dl.head;
node<T>*cur=dlcur;
//  cout<<head->data<<endl;
int xx=length()-1;
while(xx--)
{
// cout<<"wzzx"<<xx<<endl;
dlcur=dlcur->next;
dlcur=cur;
cur=cur->next;
//cout<<cur->data<<endl;
}

}

}
int length()
{
int ret=0;
if(head)
{
node<T>*cur=head;
while(cur)
{
ret++;
cur=cur->next;
}

return ret;
}
else return 0;
}

void pushback(const T &d)
{
if(head==NULL)
{
head=new node<T>(d);
tail=head;
}
else
{
tail->next=new node<T>(d);
tail->next->prve=tail;
tail=tail->next;
}
}
T popback()
{
if(head==NULL)
{
return 0;
}
else
{
return tail->data;

}

}
void pushfront(const T &d)
{
if(head==NULL)
{
head=new node<T>(d);
tail=head;
}
else
{
head->prve=new node<T>(d);
head->prve->next=head;
head=head->prve;
}
}
T popfront()
{
if(head==NULL)
{
return 0;
}
else
{
return head->data;

}

}
void insert(int x, const T d)
{
if(x<0||x<length())
{x=x-1;
node<T> *add=new node<T>(d);
node<T> *cur=head;
if(head)
{
while(x--)
{cur=cur->next;}
add->prve=cur;        add->next=cur->next;
cur->next=add;
}
}
}
void reverse()
{
int len=length();
node<T> *tmp=NULL;
if(head)
{
node<T>* cur = head;
node<T>*   p = head;
while(len--)
{
p = p->next;
tmp=cur->next;
cur->next=cur->prve;
cur->prve=tmp;
cur=p;
}
p=head;
head=tail;
tail=p;
}

}

};
void test()
{
dlist<int> int_dlist;
cout<<"** 1 : ***************"<<endl;
int_dlist.pushback(11);
int_dlist.pushback(22);
int_dlist.pushback(33);
int_dlist.pushback(44);
int_dlist.print();
cout<<"*** 2 :**************"<<endl;

int_dlist.pushfront(55);
int_dlist.pushfront(66);
int_dlist.pushfront(77);
int_dlist.print();
cout<<"*** 3 :**************"<<endl;
cout<<int_dlist.popfront()<<endl;
cout<<int_dlist.popback()<<endl;
cout<<"*** 4 :**************"<<endl;

}
int main()
{
dlist<int> int_dlist;
cout<<"** 5 : ***************"<<endl;
int_dlist.pushback(11);
int_dlist.pushback(22);
int_dlist.pushback(11);
int_dlist.pushback(22);
int_dlist.print();
dlist<int> int_dlist2;
int_dlist2=int_dlist;
int_dlist.print();
cout<<"** 6 : ***************"<<endl;
cout<<int_dlist.length()<<endl;
cout<<"** 7 : ***************"<<endl;
int_dlist.reverse();
int_dlist.print();
cout<<"** 8 : ***************"<<endl;
int_dlist.insert(3,99);

int_dlist.print();

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: