#include<iostream>
using namespace std;
//单链表
class point{//结点类
public:
int data;
point *next;
};
class line{//单链表
public:
int length;
point *head;
line();
void show();//输出元素
void creat_line(int n);//创建单链表
void insert_elem(int i,int n);//插入元素
void delete_elem(int i);//删除元素
void delete_line();//删除单链表
void print_length();//打印单链表长度
};
line::line(){//建立一个空表
head=new point;
length=0;
head->data=0;
head->next=NULL;
}
void line::creat_line(int n){//建立一个单链表
if(n<0){
cout<<"输入不合法"<<endl;
return;
}
point *temp,*new_elem;
temp=head;//从头指针开始增加元素
for(int i=0;i<n;i++){
int m=0;
new_elem=new point;
cout<<"请为第"<<i+1<<"个元素赋值:";
cin>>m;
new_elem->data=m;
new_elem->next=NULL;
temp->next=new_elem;
temp=new_elem;
length++;
}
}
void line::show(){//遍历输出单链表中的元素
if(head==NULL){
cout<<"此表为一个空表"<<endl;
return;
}
point *temp=head;
while(temp->next != NULL){
temp=temp->next;
cout<<temp->data<<" ";
}
}
void line::insert_elem(int i,int n){//把元素值为n的数据插入到第i个元素之前
if(i<0||i>=length+1){
cout<<"插入的位置不存在"<<endl;
return;
}
point *temp,*new_elem;
temp=head;
for(int i1=1;i1<i;i1++){
temp=temp->next;
}
new_elem=new point;
new_elem->data=n;
new_elem->next=temp->next;
temp->next=new_elem;
length++;
}
void line::delete_elem(int i){//删除第i个元素
if(head==NULL){
cout<<"此表已经是空表了"<<endl;
return;
}
point *temp,*p;
temp=head;
for(int i1=1;i1<i;i1++){
temp=temp->next;
}
p=temp->next;
temp->next=temp->next->next;
delete p;
p=NULL;
length--;
}
void line::delete_line(){//整表删除
if(head==NULL){
cout<<"此表为空表了"<<endl;
return;
}
point *temp1,*tem;
temp1=head->next;
tem=new point;
while(temp1!=NULL){
tem=temp1;
temp1=temp1->next;
head->next=temp1;
tem->next=NULL;
delete tem;
}
head->next=NULL;
}
void line::print_length(){
cout<<"表的长度为"<<length<<endl;
}
int main(){
line l;
l.creat_line(4);
l.insert_elem(2,100);
l.delete_elem(4);
l.show();
l.print_length();
return 0;
}