#include<iostream>
using namespace std;
#define OK 1
#define ERROR -1
typedef char Elemtype;
typedef int Status;
typedef struct LNode
{
Elemtype data;
struct LNode *next;
}LNode, *Linklist;
Status CreateList(Linklist &L)
{
Linklist p,q;
Elemtype data;
L = (Linklist)malloc(sizeof(LNode));
L->next = NULL;
q = L;
while((data = getchar()) != '#')
{
p = (Linklist)malloc(sizeof(LNode));
p->data = data;
q->next = p;
q = p;
}
q->next = NULL;
return OK;
}
void PrintList(Linklist &L)
{
Linklist p;
p = L->next;
while(p)
{
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
}
Status GetElem(Linklist L,Elemtype *str)
{
int count,i;
Linklist p;
p = L->next;
count = 1; //count计数
cout<<"请输入查找编号"<<endl;
cin>>i;
while(p && count < i)
{
p = p->next;
count++;
}
if(count > i)
return ERROR;
*str = p->data;
cout<<"第"<<i<<"个元素为:"<<*str<<endl;
return OK;
}
//删除链表中的元素
Status DeleList(Linklist &L,Elemtype *str)
{
int i,count = 0;
Linklist pr,p;
pr = L;
cout<<"请输入要删除的编号"<<endl;
cin>>i;
while(pr && count< i - 1)
{
pr = pr->next;
count ++;
}
p = pr->next;
*str = p->data;
pr->next = p->next;
cout<<"删除的元素为:"<<*str<<endl;
return OK;
}
//在指定位置插入元素
Status InsertList(Linklist &L)
{
int i,count = 0;
char str;
Linklist pr,p; //pr为要插入的前一个结点
pr = L;
cout<<"请输入要插入的位置:"<<endl;
cin>>i;
cout<<"请输入要插入的元素:"<<endl;
cin>>str;
while(pr && count < i-1)
{
pr = pr->next;
count ++;
}
p = (Linklist)malloc(sizeof(LNode));
p->data = str;
p->next = pr->next;
pr->next = p;
return OK;
}
Status CompList(Linklist L)
{
char str;
int mark = 1;
int count = 0;
Linklist p;
p = L;
cout<<"请输入要查询的元素:"<<endl;
cin>>str;
while(p->next)
{
p = p->next;
count++;
if(p->data == str)
{
mark = 0;
return count;
}
}
if(mark == 1)
{
cout<<"未找到此元素"<<endl;
return ERROR;
}
}
int main()
{
int findmark;
char Gstr,Dstr;
Linklist L;
CreateList(L);
PrintList(L);
GetElem(L,&Gstr);
DeleList(L,&Dstr);
PrintList(L);
InsertList(L);
PrintList(L);
findmark = CompList(L);
cout<<findmark<<endl;
return 0;
}
链表的基本操作(包含创建,查找,删除等)
最新推荐文章于 2024-05-06 23:01:48 发布