#include<string>
using namespace std;
typedef int ElemType;
typedef struct Node
{
ElemType data;
Node *next;
}Link_List;
Link_List* Init_List()//初始化链表
{
Link_List *L=(Node*)malloc(sizeof(Node));
L->next=NULL;
cout<<"初始链表!"<<endl;
return L;
}
int List_Empty(Link_List *L)//判空
{
if(!L)
{
cout<<"链表不存在!"<<endl;
exit(-1);
}
if(L->next ==NULL)
{
cout<<"链表为空!"<<endl;
return 1;
}
else
{
cout<<"链表不为空!"<<endl;
return 0;
}
}
int Creat_List(Link_List *L)//创建链表
{
cout<<"创建链表!"<<endl;
if(!L)
{
cout<<"链表不存在!"<<endl;
exit(-1);
}
Node *p,*new_p;
p=new_p =(Node*)malloc( sizeof( Node));
L->next =p;
cin>>new_p->data;
while(new_p->data !=0)
{
new_p =(Node*)malloc( sizeof( Node));
cin>>new_p->data;
p->next=new_p;
p=new_p;
}
p->next=NULL ;
cout<<"创建完毕 !"<<endl;
return 0;
}
int List_Lenth(Link_List *L)//求表长
{
if(!L)
{
cout<<"链表不存在!"<<endl;
return 0;
}
Node*p;
int i=0;
p=L;
while(p=p->next)
{
i++;
}
// cout<<"表长为:"<<i<<endl;
return i;
}
int Locate_Elem(Link_List *L,ElemType e)//查找数据
{
cout<<"数据查找"<<endl;
if(!L)
{
cout<<"链表不存在!"<<endl;
exit(-1);
}
Node *p;
int i=0;
p=L->next;
while(p->data!=e)
{
p=p->next;
i++;
}
if(i>=0&&i<=List_Lenth(L))
{
cout<<"数据的位置为:"<<i<<endl;
return i;
}
else
{
cout<<"查找的数据不存在!"<<endl;
exit(-1);
}
}
ElemType Get_Elem(Link_List *L,int i)//取元素
{
cout<<"取指定元素"<<endl;
Node *p;
p=L->next;
if(!L)
{
cout<<"链表不存在!"<<endl;
exit(-1);
}
if(i>=1&&i<=List_Lenth(L))
{
for(int n=1;n<i;n++)
p=p->next;
cout<<"取得元素为"<<i<<endl;
return p->data;
}
else
{
cout<<"i取值越界!"<<endl;
exit(-1);
}
}
int Insert_Elem(Link_List *L,int i,ElemType e)//插入数据
{
cout<<"插入数据"<<endl;
if(!L)
{
cout<<"链表不存在!"<<endl;
exit(-1);
}
Node *p,*new_p;
p=L->next ;
for(int n=0;n<i;n++)
p=p->next;
new_p =(Node*)malloc(sizeof( Node));
new_p->data=e;
new_p->next=p->next;
p->next=new_p;
return 0;
}
int Delet_Elem(Link_List *L,int i)//删除数据
{
if(!L)
{
cout<<"链表不存在!"<<endl;
exit(-1);
}
if(0!=List_Lenth(L))
{
cout<<"删除数据"<<endl;
Node *p,*old_p;
p=L;
for(int n=0;n<i-1;n++)
p=p->next;
old_p=p->next;
cout<<"删除的数据为"<<old_p->data<<endl ;
p->next=p->next->next;
free(old_p);
}
else
{
cout<<"链表已,无法删除!"<<endl;
}
return 0;
}
int Clear_List(Link_List *L)//清空链表
{
cout<<"清空链表"<<endl;
if(!L)
{
cout<<"链表不存在!"<<endl;
exit(-1);
}
do
{
Delet_Elem(L,List_Lenth(L));
}
while(!List_Empty(L));
cout<<"链表清空完成!"<<endl;
return 1;
}
int Destroy_List(Link_List * L)//销毁链表/////
{
cout<<"销毁链表"<<endl;
if(!L)
{
cout<<"链表不存在!"<<endl;
exit(-1);
}
if(0!=List_Lenth(L))
{
Clear_List(L);
}
free(L);
//L=NULL;
cout<<"成功销毁链表"<<endl;
return 0;
}
int main()
{
Link_List * L=NULL;
L=Init_List();
List_Empty(L);
Creat_List(L);
Delet_Elem(L,List_Lenth(L));
Insert_Elem(L,2,4);
Locate_Elem(L,3);
Get_Elem(L,2);
Clear_List(L);
Destroy_List(L);
return 0;
}