/*3. 按照课本第2.3.1节定义的单链表结构,完成对单链表结构的定义,以及对单链表的各种基本运算的实现(每种基本运算用一个函数来实现)。
基本运算包括
:建表Create运算、
初始化InitList运算、
求表长Length运算、
插入新节点Insert运算、
删除节点Delete运算、
按序号查找Get运算、
定位(按值查找)Locate运算、
输出单链表中所有结点的数据元素值Display运算、
销毁Destroy运算。*/
#include<iostream>
using namespace std;
typedef char datatype;
typedef struct node* pointer;
struct node
{
datatype data;
pointer next;
};
typedef node* lklist;
lklist Creat()
{//尾插法建表,有头结点
pointer head,rear,s; char ch;
head=new node; //生成头结点
rear=head; //尾指针初值
cout<<"请依次输入链表中的元素,每个元素是一个字符,以输入$表示结束:"<<endl;
while(cin>>ch,ch!=')
{ //读入并检测结束
s=new node; s->data=ch; //生成新结点
rear->next=s; rear=s; //插入表尾,改尾指针
}
rear->next=NULL; //尾结点的后继为空
return head;
}
lklist InitList()
{
pointer head;
head=new node;
head->next=NULL;
return head;
}
int Length(lklist L)
{
int j;
pointer p;
j=0;
p=L->next; //从首结点开始
while(p!=NULL) //逐点检测、计数
{
j++;
p=p->next;
}
return j;
}
pointer Get(lklist head,int i) //0≤i≤n
{
int j;
pointer p;
if(i<0) return NULL;//位置非法,无此结点
j=-1; //计数器
p=head; //从头结点(0号)开始搜索
while(p!=NULL) {
j++;if(j==i) break;
p=p->next; //未到第i点,继续
}
return p; //含找到、未找到两种情况
}
int Insert(lklist head,datatype x,int i)
{
pointer q,s;
q=Get(head,i-1); //找第i-1个点
if(q==NULL) //无第i-1点,即i<1或i>n+1时
{
cout<<"非法插入位置!\n";
return 0;
}
s=new node; //生成新结点
s->data=x;
s->next=q->next; //新点的后继是原第i个点
q->next=s; //原第i?1个点的后继是新点
return 1; //插入成功
}
int Delete(lklist head,int i)
{
pointer p,q;
q=Get(head,i-1); //找待删点的直接前趋
if(q==NULL || q->next==NULL)//即i<1或i>n时
{cout<<"非法删除位置!\n";return 0;}
p=q->next; //保存待删点地址
q->next=p->next; //修改前趋的后继指针
delete p; //释放结点
return 1; //删除成功
}
pointer Locate(lklist head,datatype x)
{
pointer p;
p=head->next; //从首结点开始搜索
while(p!=NULL)
{
if(p->data==x) break;
p=p->next; //到下一个点
}
return p; //含找到、未找到两种情况
}
int Locate2(lklist head,datatype x) {
int j;
pointer p;
j=0; //计数器
p=head->next; //从首结点开始扫描
while(p!=NULL) {
j++;
if(p->data==x) break;//找到,退出
p=p->next; //没找到,继续
}
if(p!=NULL) return j; //找到x
else return -1; //没有x,查找失败
}
void Destory(lklist & L)
{//删除所有结点
pointer p,q;
p=L;
while(p!=NULL)
{
q=p->next; //保存待删点后继
delete p; //释放空间
p=q;
}
L=NULL; //头指针置空
}
void Display(lklist head)
{
if(head==NULL)
{
cout<<"链表不存在!"<<endl;
return ;
}
pointer p;
p=head->next;
cout<<"链表中的元素依次是:";
while(p!=NULL)
{
cout<<p->data<<' ';
p=p->next;
}
cout<<endl;
}
int main()
{
lklist Lk;
cout<<"调用Creat函数,创建链表:"<<endl;
Lk=Creat();
Display(Lk);
cout<<"调用Length函数,链表的长度是:"<<Length(Lk)<<endl;
Insert(Lk, 'x',3);
cout<<"调用Insert函数,在第3个位置插入字符x之后。";
Display(Lk);
cout<<"调用Get函数,获取链表的第4个元素得到是:";
pointer p = Get(Lk,4);
cout<<p->data<<endl;
cout<<"调用Locate函数,查找链表中的字符d,得到在链表的第"<<Locate2(Lk,'d')<<"的位置。"<<endl;
Delete(Lk, 2);
cout<<"调用Delete函数,删除第2个位置的字符之后。";
Display(Lk);
Destory(Lk);
cout<<"调用Destroy函数,销毁链表后。";
Display(Lk);
return 0;
}
单链表
最新推荐文章于 2022-11-20 03:26:03 发布