/*
编写一个程序,实现单链表的各种基本运算(假设单链表的元素类型为Char)。
(1)初始化单链表h;
(2)采用尾插法依次插入元素a,b,c,d,e;
(3)输出单链表h;
(4)输出单链表h长度;
(5)判断单链表h是否为空;
(6)输出单链表h的第3个元素;
(7)输出元素a的位置;
(8)在第4个元素位置上插入元素f;
(9)输出单链表h;
(10)删除h的第3个元素;
(11)输出单链表h;
(12)释放单链表h。
*/
#include <iostream>
#include <malloc.h>
#include <cstdio>
#include <cstring>
using namespace std;
typedef char ElemType;
typedef struct LNode
{
ElemType data;
struct LNode *next;
} LinkList;
void InitList(LinkList *&L) //初始化单链表h
{
L=(LinkList *)malloc(sizeof (LinkList));
L->next=NULL;
}
void CreateListR(LinkList *&L,ElemType a[],int n) //采用尾插法依次插入元素a,b,c,d,e
{
LinkList *s,*r;
int i;
L=(LinkList *)malloc(sizeof(LinkList));
r=L;
for(i=0; i<n; i++)
{
s=(LinkList *)malloc(sizeof(LinkList));
s->data=a[i];
r->next=s;
r=s;
}
r->next=NULL;
}
void DispList(LinkList *L) //输出单链表h
{
LinkList *p=L->next;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
int ListLength(LinkList *L) //输出单链表h的长度
{
int n=0;
LinkList *p=L;
while(p->next!=NULL)
{
n++;
p=p->next;
}
return (n);
}
bool ListEmpty(LinkList *L) //判断单链表h是否为空
{
return(L->next==NULL);
}
void Disp3(LinkList *L,int j) //输出单链表h的第3个元素
{
LinkList *p=L->next;
int i=1;
while(i<j&&p!=NULL)
{
i++;
p=p->next;
}
cout<<p->data<<endl;
}
void Displocation(LinkList *L,ElemType a) //输出元素a的位置
{
LinkList *p=L->next;
int i=1;
while(p!=NULL)
{
if(p->data==a)
cout<<i<<" ";
p=p->next;
i++;
}
cout<<endl;
}
bool ListInsert(LinkList *&L,int i,ElemType e) //插入数据元素
{
int j;
LinkList *p=L,*s;
while(j<i-1&&p!=NULL)
{
j++;
p=p->next;
}
if(p==NULL)
return false;
else
{
s=(LinkList *)malloc(sizeof(LinkList));
s->data=e;
s->next=p->next;
p->next=s;
return true;
}
}
bool ListDelete(LinkList *&L,int i) //删除数据元素
{
int j=0;
LinkList *p=L,*q;
while(j<i-1&&p!=NULL)
{
j++;
p=p->next;
}
if(p==NULL)
return false;
else
{
q=p->next;
if(q==NULL)
return false;
p->next=q->next;
free(q);
return true;
}
}
void DestoryList(LinkList *&L) //销毁单链表
{
LinkList *p=L,*q=L->next;
while(q!=NULL)
{
free(p);
p=q;
q=p->next;
}
free(p);
}
int main()
{
char a[10];
char b='a';
gets(a);
LinkList *L;
InitList(L);
CreateListR(L,a,strlen(a));
cout<<"输出单链表:";
DispList(L);
cout<<"单链表的长度:"<<ListLength(L)<<endl;
cout<<"单链表是否为空:";
if(ListEmpty(L))
cout<<"是"<<endl;
else
cout<<"否"<<endl;
cout<<"单链表L的第三个元素为:";
Disp3(L,3);
cout<<"输出元素"<<b<<"的位置:";
Displocation(L,b);
ListInsert(L,4,'f');
cout<<"已在第4个元素位置上插入元素f"<<endl;
cout<<"输出单链表:";
DispList(L);
ListDelete(L,3);
cout<<"已删除第3个位置上的元素"<<endl;
cout<<"输出单链表:";
DispList(L);
DestoryList(L);
cout<<"单链表已释放!"<<endl;
return 0;
}
运行结果: