您的位置:首页 > 编程语言 > C语言/C++

C++链表

2016-01-25 02:55 507 查看

code

/*************************************************************************
> File Name: listplus.cpp
> Author: Fan Deliang
> Mail: fan0816fan@163.com
> Created Time: 2016年01月22日 星期五 23时41分04秒
************************************************************************/

#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=100;

//define node structure
struct node{
int data;
struct node *next;
};

//define list class
class list{
struct node *head;
int num;//链表大小
public:
list();//construction1
list(int n);//construction2
list insert(int _data,int a);//insert
list del(int a);//delete
void display();//display
~list();//distruction
};

//class functions
list::list(){
num=0;
head=0;
}
list::list(int n){
num=0;
head=0;
struct node *p;
struct node *q;
q=head;
for(int i=0;i<n;i++,num++){
int temp_data;
cin>>temp_data;
p=(struct node*)new(struct node);
p->data=temp_data;
p->next=0;
if(head==0)head=p;
else q->next=p;
q=p;
}
}
list list::insert(int _data,int a){
struct node *t;
t=head;
while(t!=0){
if(t->data==_data){
struct node *p2=(struct node*)new(struct node);
p2->data=a;
p2->next=t->next;
t->next=p2;
num++;
return *this;
}
else t=t->next;
}
struct node *p=(struct node*)new(struct node);
p->data=a;
p->next=0;
t=p;
if(num==0)head=t;
return *this;
}
list list::del(int _data){
if(head==0)return *this;
struct node *t1,*p1;
t1=head;
while(t1->data==_data){
head=t1->next;
delete(t1);num--;
struct node *t1=head;
}
while(t1->next!=0){
if(t1->next->data==_data){
p1=t1->next;
t1->next=p1->next;
delete(p1);
num--;
struct node *p1;
}
else t1=t1->next;
}
return *this;

}
void list::display(){
struct node *t2;
t2=head;
while(t2!=0){
printf("%d ",t2->data);
//cout<<t->data<<" ";
t2=t2->next;
}
cout<<endl;
}
list::~list(){
cout<<endl<<endl<<"bye-bye"<<endl<<endl;
/*while(head!=0){
struct node *t3;
t3=head;
head=t3->next;
delete(t3);
num--;
}*/
}

//main function
int main()
{
list L1;
list L2(10);

cout<<"L1 is :"<<endl;
L1.display();
cout<<"L2 is :"<<endl;
L2.display();

L1.insert(4,4);
cout<<"L1 is :"<<endl;
L1.display();
L2.insert(4,4);
cout<<"L2 is :"<<endl;
L2.display();

L1.del(4);
cout<<"L1 is :"<<endl;
L1.display();
L2.del(4);
cout<<"L2 is :"<<endl;
L2.display();

return 0;
}


C++初步链表

链表类的初始化(两种方式),链表元素的插入,删除,链表元素的展示。

问题

中间我把析构函数给注释掉了。

因为,我刚发现函数调用时,调用析构函数的境况和我想象的不太一样。

为什么会是这样调用的呢?

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