C++中的类就是C中结构体的化身,两者区别在于
C++中的成员默认为私有(private)
结构体中默认为(public)
#include<iostream>
using namespace std;
struct node//结构体默认公有
{
node();
node(int);
int data;
struct node* next;//单纯存地址,不指向任何空间
};
typedef struct node* pnode;
node::node():data(0),next(NULL){}
node::node(int data):data(data),next(NULL){}
class list
{
public:
list();
list(list&);
bool insert(int);//头插
bool insert1(int);//尾插
bool delet(int);//删除某元素
bool delet(int,int&);//删除第几个元素
void show();
int show_len();
private:
pnode head;
pnode rear;
int len;
};
list::list():head(NULL),rear(NULL),len(0){}
list::list(list& p):len(p.len),head(NULL),rear(NULL)//拷贝构造中头也要置空!!
{
pnode tmp=p.head;
while(NULL!=tmp && this->insert1(tmp->data))//边遍历边拷贝//头插法的拷贝
tmp=tmp->next;
this->len++;
}
bool list::insert(int data)//头插法
{
pnode newnode=new node(data);//C++中可省略struct,系统会自动识别
if(NULL==newnode)
return false;
this->len++;
newnode->next=head;
head=newnode;
return true;
}
bool list::insert1(int data)//尾插法
{
pnode newnode=new node(data);
if(NULL==newnode)
return false;
if(NULL==head)
head=newnode;
else
rear->next=newnode;
rear=newnode;
this->len++;
return true;
}
bool list::delet(int key)//删除某个元素
{
pnode front,ploc;
front=NULL;
ploc=head;
while(ploc!=NULL && key!=ploc->data)
{
front=ploc; //你追我赶
ploc=ploc->next;
}
if(NULL==ploc)
return false;
if(ploc==head)
head=head->next;
else
front->next=ploc->next;
delete ploc;
this->len--;
return true;
}
bool list::delet(int pos,int& data)//删除第几个元素
{
pnode pfront=NULL,ploc=this->head;
int i=1;
while(i!=pos && ploc!=NULL)
{
pfront=ploc;
ploc=ploc->next;
i++;
}
if(NULL==ploc)//下标超出
return false;
data=ploc->data;//保存删除元素
if(ploc==this->head)//如果要删除头结点
{
this->head=this->head->next;
}
else
pfront->next=ploc->next;
delete ploc;
this->len--;
return true;
}
void list::show()
{
pnode tmp=head;
while(tmp)
{
cout<<tmp->data<<" ";
tmp=tmp->next;
}
cout<<endl;
}
int list::show_len()
{
return this->len;
}
int main()
{
list l;
l.insert1(1);
l.insert1(2);
l.insert1(3);
l.insert1(4);
int i;
l.delet(2);
l.delet(2,i);
l.show();
cout<<l.show_len();
}