#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;
}