#include <iostream>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode *next;
}LNode,*LinkList;
Status InitList(LinkList &L)
{
L= new LNode;
L->next=NULL;
return OK;
}
Status GetElem(LinkList L,int i,ElemType &e){
LNode *p;
int j;
p=L->next;j=1;
while(p&&j<i)
{
p=p->next;++j;
}
if(!p || j>i) return ERROR;
e=p->data;
return OK;
}
Status LocateElem(LinkList L,ElemType e){
LNode *p;
int j;
p=L->next; j=1;
while(p &&p->data!=e)
{
p=p->next;
j++;
}
if(p) return j;
else return 0;
}
Status ListInsert(LinkList &L,int i,ElemType e){
LNode *p,*s;
int j;
p = L;j = 0;
while(p &&j < i-1)
{ p = p->next;++j;}
if(!p || j > i-1)
return ERROR;
s =new LNode;
s->data = e; s->next = p->next;
p->next = s;
return OK;
}
Status ListDelete(LinkList &L,int i){
LNode *p,*q;
int j;
p = L; j=0;
while(p->next && j <i-1)
{
p = p->next;++j;
}
if(!(p->next) || j > i-1)
return ERROR;
q = p->next;p->next = q->next;
delete q;
return OK;
}
void CreateList_R(LinkList &L,int n){
LNode *r,*p;
int i;
L=new LNode;
L->next=NULL;
r=L;
for(i=0;i<n;i++){
p=new LNode;
cin>>p->data;
p->next=NULL;r->next=p;
r=p;
}
}
void TraverList(LinkList L)
{
LNode *p;
p=L->next;
while(p)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
void menu()
{
cout<<"******************************"<<endl;
cout<<" 0:退出"<<endl;
cout<<" 1:初始化"<<endl;
cout<<" 2:建表"<<endl;
cout<<" 3:遍历"<<endl;
cout<<" 4:按位置查找元素"<<endl;
cout<<" 5:插入元素:"<<endl;
cout<<" 6:删除元素:"<<endl;
cout<<" 7:按值查找元素"<<endl;
cout<<"******************************"<<endl;
}
int main(){
LinkList L;
int choose,i,e,n;
menu();
while(1)
{
cout<<"选择要执行的基本操作:";
cin>>choose;
switch(choose)
{
case 1:
InitList(L);
break;
case 2:
cout<<"输入表中元素的个数:";
cin>>n;
CreateList_R(L,n);
break;
case 3:
TraverList(L);
break;
case 4:
cout<<"输入要查找的元素位置:"<<endl;
cin>>i;
if(GetElem(L,i,e))
cout<<"第"<<"i"<<"位的元素值为:"<<e<<"。"<<endl;
else
cout<<"该元素不存在!"<<endl;
break;
case 5:
cout<<"输入要插入元素的位置和值:"<<endl;
cin>>i>>e;
if(ListInsert(L,i,e)==OK)
TraverList(L);
else
cout<<"不能插入!"<<endl;
break;
case 6:
cout<<"输入要删除元素的位置:"<<endl;
cin>>i;
if(ListDelete(L,i)==OK)
TraverList(L);
else
cout<<"删除位置不合法。"<<endl;
break;
case 7:
cout<<"输出要查找元素的值:"<<endl;
cin>>e;
if(LocateElem(L,e))
cout<<"该元素的位置是第"<<LocateElem(L,e)<<"位。"<<endl;
else
cout<<"该元素不存在!"<<endl;
break;
case 0:
cout<<"操作结束!"<<endl;
}
}
return 0;
}