|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include<iostream>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef int ElemType;
typedef struct LNode
{
int data;
struct LNode *next;
}LNode,* LinkList;
Status InitList_L(LinkList &L)
{
L=new LNode;
L->next=NULL;
return OK;
}
Status GetElem_L(LinkList L,int i,ElemType &e)
{
int j;
LNode *p;
p=L->next;
j=1;
while(j<i&&p)
{
p=p->next;
++j;
}
if(!p||j>i) return ERROR;
e=p->data;
return OK;
}
LNode *LocateElem_L(LinkList L,ElemType e)
{
LNode *p;
p=L->next;
while(p&&p->data!=e)
p=p->next;
return p;
}
Status ListInsert_L(LinkList &L,int i,int &e)
{
int j;
LNode *p,*s;
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_L(LinkList &L,int i,ElemType &e)
{
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;
e=q->data;
delete q;
return OK;
}
Status ListDelete_L(LinkList &L,int i,ElemType &e)
{
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;
e=q->data;
delete q;
return OK;
}
void CreateList_F(LinkList &L,int n)
{
LNode *p;
L=new LNode;
L->next=NULL;
cout<<"请输入"<<n<<"个数"<<endl;
for(int i=n;i>0;--i)
{
p=new LNode;
cin>>p->data;
p->next=L->next;
L->next=p;
}
}
void CreateList_L(LinkList &L,int n)
{
LNode *r,*p;
L=new LNode;
L->next=NULL;
r=L;
cout<<"请输入"<<n<<"个数\n";
for(int i=0;i<n;i++)
{
p=new LNode;
cin>>p->data;
p->next=NULL;
r->next=p;
r=p;
}
}
int main()
{
int res,a,b,choose;
LNode *L,*p;
cout<<"1,建立链表"<<endl;
cout<<"2,输入数据"<<endl;
cout<<"3,按位置查找"<<endl;
cout<<"4,按值查找"<<endl;
cout<<"5,链表的插入"<<endl;
cout<<"6,链表的删除"<<endl;
cout<<"7,输出数据"<<endl;
cout<<"0,退出"<<endl<<endl;
choose=-1;
while(choose!=0)
{
cout<<"请选择";
cin>>choose;
switch(choose)
{
case 1:
if(InitList_L(L))
cout<<"成功建立链表!\n\n";
break;
case 2:
CreateList_L(L,10);
cout<<"成功创建链表\n\n";
break;
case 3:
cout<<"请输入一个位置来查找";
cin>>a;
if(GetElem_L(L,a,res))
cout<<"查找成功!第"<<a<<"个数是:"<<res<<"\n\n";
else
cout<<"查找失败\n\n";
break;
case 4:
cout<<"请输入一个数来查找:";
cin>>b;
if(LocateElem_L(L,b)!=NULL)
cout<<"查找成功\n\n";
else
cout<<"查找失败\n\n";
break;
case 5:
cout<<"请输入两个数分别代表插入位置和数值:";
cin>>a>>b;
if(ListInsert_L(L,a,b))
cout<<"成功将"<<b<<"插入到"<<a<<"个位置\n\n";
else
cout<<"插入失败\n\n";
case 6:
cout<<"请输入一个位置删除";
cin>>a;
if(ListDelete_L(L,a,res))
cout<<"删除成功,删除的数位:"<<res<<"\n\n";
else
cout<<"删除失败\n\n";
break;
case 7:
cout<<"链表里的数为:\n";
p=L->next;
while(p)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
break;
}
}
return 0;
}
|
-
|