实现单链表的各种基本运算的算法

#include<iostream>
using namespace std;
#include<malloc.h>
typedef char Elem;
typedef struct AA{
Elem data;
struct AA *next;
}A;
void Create(A *&L)
{
L=(A *)malloc(sizeof(A));
L->next=NULL;
}
bool InsertList(A *&L,Elem e,int i)
{
A *s,*p=L;
int j=0;
if(i<=0)
return false;
while(j<i-1&&p!=NULL)
{
j++;
p=p->next;
}
if(p==NULL)
return false;
else
{
s=(A *)malloc(sizeof(A));
s->data=e;
s->next=p->next;
p->next=s;
return true;
}

}
void DisPlay(A *L)
{
A *s=L->next;
while(s!=NULL)
{
cout<<s->data<<" ";
s=s->next;
}
cout<<endl;
}
void DisPlayA(A *L)
{
int i=0;
A *p=L;
while(p->next!=NULL)
{
i++;
p=p->next;
}
cout<<i<<endl;
}
void empty1(A *L)
{
if(L->next==NULL)
cout<<"The list is empty!"<<endl;
else
cout<<"The list is not empty!"<<endl;
}
void DisPlayA(A *L,int i)
{
int j=1;
A *p=L->next;
while(j<i)
{
p=p->next;
j++;
}
cout<<"The third element is "<<p->data<<"."<<endl;
}
void Location(A *L,Elem e)
{
int i=1;
A *p=L->next;
while(p!=NULL&&p->data!=e)
{
p=p->next;
i++;
}
cout<<"The location of element 'a' is: "<<i<<endl;
}
void Del(A *&L,int i)
{
A *p=L->next;
int j=1;
while(j<i-1&&p!=NULL)
{
p=p->next;
j++;
}
p->next=p->next->next;
}
void Des(A *&L)
{
A *pre=L,*p=L->next;
while(p!=NULL)
{
free(pre);
pre=p;
p=p->next;
}
free(pre);
}
int main()
{
A *s1;
Elem e;
int i=0;
Create(s1);
for(int i=1;i<6;i++)
{
cin>>e;
InsertList(s1,e,i);
}
DisPlay(s1);
empty1(s1);
DisPlayA(s1,3);
Location(s1,'a');
InsertList(s1,'f',4);
DisPlay(s1);
Del(s1,3);
DisPlay(s1);
Des(s1);
}

原文地址:https://www.cnblogs.com/xww115/p/10546656.html