//1.头文件
#include <iostream>
using namespace std;
//2.宏定义
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int Status;
typedef int ElemType;
//3.单链表的类型定义
typedef struct LNode
{
ElemType data; //Data为数据域
struct LNode *next;// next为指针域
}LNode,*LinkList;
//4.初始化
Status InitList(LinkList &L)
{
L= new LNode;
L->next=NULL;
return OK;
}
//5.取值
Status GetElem(LinkList L,int i,ElemType &e){
LNode *p;
int j;
p=L->next;j=1; //初始化
while(p&&j<i)
{ //向后扫描,直到p指向第i个元素或p为空
p=p->next;++j;
}
if(!p || j>i) return ERROR; //第i个元素不存在
e=p->data; //取第i个元素
return OK;
}
//6.查找
Status LocateElem(LinkList L,ElemType e){
//查找成功,返回L中值为e的结点的位序;查找失败,返回0
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;
}
//7.插入
Status ListInsert(LinkList &L,int i,ElemType e){
//在带头结点的单链表L中第i个数据元素之间插入数据元素e
LNode *p,*s;
int j;
p = L;j = 0;
while(p &&j < i-1)
{ p = p->next;++j;} //寻找第i-1个结点
if(!p || j > i-1)
return ERROR; //i小于1或者大于表长
s =new LNode; //生成新结点
s->data = e; s->next = p->next; //插入L中
p->next = s;
return OK;
}//LinstInsert_L
//8.删除
Status ListDelete(LinkList &L,int i){
//在带头结点的单链表L中,删除第i个元素,并由e返回其值
LNode *p,*q;
int j;
p = L; j=0;
while(p->next && j <i-1)
{ //寻找第i个结点,并令p指向其前驱
p = p->next;++j;
}
if(!(p->next) || j > i-1)
return ERROR; //删除位置不合理
q = p->next;p->next = q->next; //删除并释放结点
delete q;
return OK;
} // ListDelete_L
//9.建表(尾插法)
void CreateList_R(LinkList &L,int n){
//正位序输入n个元素的值,建立带表头结点的单链表L
LNode *r,*p;
int i;
L=new LNode;
L->next=NULL;
r=L; //尾指针r指向头结点
for(i=0;i<n;i++){
p=new LNode; //生成新节点
cin>>p->data; //输入元素值
p->next=NULL;r->next=p; //插入到表尾
r=p; //r指向新的尾结点
}
}//CreateList_R
//11.遍历
void TraverList(LinkList L)
{
LNode *p;
p=L->next;
while(p)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
//12.菜单
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;
}
//13.主函数
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;
}
单链表代码
最新推荐文章于 2024-07-18 00:08:52 发布