一.题目要求
实现单链表各种基本运算的算法】
问题描述:该算法的设计,要求运行结果如下所示:
单链表的基本运算如下:
(1)初始化单链表head
(2)依次采用尾插法插入a,b,c,d,e元素
(3)输出单链表head:a b c d e
(4)单链表head长度:5
(5)单链表head为非空
(6)单链表head的第3个元素:c
(7)元素a的位置:1
(8)在第4个元素位置上插入f元素
(9)输出单链表head:a b c f d e
(10)删除head的第3个元素
(11)输出单链表head:a b f d e
(12)释放单链表head
二.代码实现
#include<bits/stdc++.h>
using namespace std;
typedef char ElemType;
typedef struct Lode
{
ElemType data;
struct Lode* next;
}Link,*LinkList;
bool init_head(LinkList &L);
int tail_insert(LinkList &L,ElemType a[6]);
bool display(LinkList L);
int Link_length(LinkList L);
bool Link_empty(LinkList &L);
ElemType get_Link_elem(LinkList &L,int e);
int locate_Link(LinkList &L,ElemType e);
bool Link_insert(LinkList &L,int e);
bool delet_Link(LinkList &L,int e);
bool destroy(LinkList &L);
int main()
{
LinkList L;
ElemType a[6]={"abcde"};
init_head(L);
tail_insert(L,a);
display(L);
cout<<"display the length of the LinkList!"<<endl;
cout<<Link_length(L)<<endl;
cout<<"please show the third elem!"<<endl;
cout<<get_Link_elem(L,3)<<endl;
cout<<"please show the location of the a!"<<endl;
cout<<locate_Link(L,'a')<<endl;
cout<<"please insert the f in the forth location!"<<endl;
Link_insert(L,4);
display(L);
cout<<"please delete the third one!"<<endl;
delet_Link(L,3);
display(L);
cout<<"destroy the LinkList!"<<endl;
destroy(L);
return 0;
}
bool init_head(LinkList &L)
{
L=(LinkList)malloc(sizeof(Link));
if(!L)
{
cout<<"allocation failure!"<<endl;
return 0;
}
else L->next=NULL;
L->data=' ';
return 1;
}
int tail_insert(LinkList &L,ElemType a[6])
{
LinkList p;
int i;
p=L;
for(i=0;i<5;i++)
{
LinkList q=(LinkList)malloc(sizeof(Link));
q->data=a[i];
q->next=p->next;
p->next=q;
p=q;
}
p->next=NULL;
return 0;
}
bool display(LinkList L)
{
LinkList p=L;
while(p)
{
cout<<p->data<<' ';
p=p->next;
}
cout<<endl;
return 1;
}
int Link_length(LinkList L)
{
LinkList p=L;
int length=0;
while(p)
{
p=p->next;
++length;
}
return length-1;
}
bool Link_empty(LinkList &L)
{
return Link_empty;
}
ElemType get_Link_elem(LinkList &L,int e)
{
LinkList p=L;
int i;
for(i=0;i<e;i++)
{
p=p->next;
}
return p->data;
}
int locate_Link(LinkList &L,ElemType e)
{
LinkList p=L;
int lc=0;
while(p->data!=e)
{
lc++;
p=p->next;
}
return lc;
}
bool Link_insert(LinkList &L,int e)
{
LinkList p=L;
int i=0;
for(;i<e;i++)
p=p->next;
LinkList q=(LinkList)malloc(sizeof(Link));
q->data ='f';
q->next=p->next;
p->next=q;
return 1;
}
bool delet_Link(LinkList &L,int e)
{
LinkList p=L;
int i;
for(i=0;i<e-1;i++)
p=p->next;
LinkList q=p->next;
p->next=q->next;
free(q);
return 1;
}
bool destroy(LinkList &L)
{
LinkList p=L;
while(p)
{
p=p->next;
free(p);
}
return 1;
}
三.运行