Код:
#include <iostream>
using namespace std;
struct SNode {
SNode*next;
int val;
SNode(){ next = NULL; val = 0;};
SNode(SNode* ne,int a){val=a; next=ne;}
};
class SList
{
SNode* head;
SNode* tail;
public:
SList();
SList(int);
SList(const SList&); //конструктор копирования
~SList();
bool is_empty();
void add_front(int);
int remove_front();
bool find(int);
int get_nth(int);
int size();
void print_slist();
SList& operator=(const SList&); //опрератор присваивания
};
SList::SList(){
head=new SNode();
tail=head;
}
SList::SList(int a){
tail=new SNode();
head=new SNode(tail,a);
}
//+++++++++++++++++++++++++++++
SList::SList(const SList& t) {
while(t.head!=t.tail)
{
//head=t.head;
//head=head->next;
head=new SNode(head,t.head->val);
}
tail = t.tail;
}
//++++++++++++++++++++++++++++++
bool SList::is_empty(){
return (head==tail)?true:false;
}
void SList::add_front(int a){
SNode *q=head;
head=new SNode(q,a);
}
int SList::remove_front(){
SNode* q=head;
head=head->next;
int a=q->val;
delete q;
return a;
}
bool SList::find(int a){
SNode* q=head;
while(q!=tail)
{
if(q->val==a)
return true;
else
q=q->next;
}
return false;
}
int SList::get_nth(int a){
SNode* q=this->head;
for(int i=0;i<a;i++)
q=q->next;
return q->val;
}
int SList::size(){
SNode *q=head;
int k=0;
for(;q!=tail;q=q->next,k++)
;
return k;
}
void SList::print_slist()
{
int size=this->size();
for(int i=0;i<size;i++)
{
cout<<this->get_nth(i)<<' ';
}
cout<<endl;
}
SList::~SList(){
while(head!=tail)
{
SNode* p=head;
head=head->next;
delete p;
}
delete tail;
}
SList& SList::operator=(const SList& t) {
// защита от неправильного самоприсваивания
if (this == & t) return *this;
else{
// освобождаем старую память
while(head!=tail)
{
SNode* p=head;
head=head->next;
delete p;
}
delete tail;
// присваиваем значения в новой памяти объекту
while(t.head!=t.tail)
{
head=t.head;
//head=head->next;
head=new SNode(head,t.head->val);
}
tail = t.tail;
return *this; }
}
int _tmain(int argc, _TCHAR* argv[])
{
SList L1;
L1.add_front(5);
L1.add_front(9);
L1.add_front(34);
SList L2;
L2.add_front(25);
L1.print_slist();
L2.print_slist();
cout<<"posle = "<<endl;
L1=L2;
L1.print_slist();
L2.print_slist();
system("pause");
return 0;
}