/*程序*/
#include<iostream>
using namespace std;struct node //创建节点
{
int date;
node *next;
};
class list //创建链表
{
int Length; //记录链表长度
node *head,*s,*p,*temp; //创建头结点 新节点 移动节点 临时节点
public:
list(){head=NULL;Length=0;} //构造函数 使头结点为空
int inser(); //插入
void output(); //打印
int LengthOut(){return Length;} //返回链表的长度
~list(){delete s;} //析构
};
int list::inser() //在链表的第i个元素之前插入元素e
{
int e, i;
p=head;
cout<<"e:";
cin>>e;
cout<<"i:";
cin>>i;
s=new node(); //动态分配新节点
s->date=e;
if(Length==0) //当链表为空时无论在哪插入都视为头结点
{ head=s;; ++Length; return Length;}
else if(i<=Length) //判断插入位置是否合理
{ for(int j=1;j<=Length;++j)
{
if(i==1) //在第一位插入时 新插入的节点作为新的头结点
{ head=s; s->next=p; ++Length; return Length;break;}
if(j==i-1)
{
temp=p->next;
p->next=s;
s->next=temp;
++Length;
return Length;
break;
}//if
p=p->next;
}//for
}//if
else
cout<<"ERROR"<<endl;
}
void list::output() //打印链表
{
cout<<"list: ";
for(p=head;p!=NULL;p=p->next)
cout<<p->date<<" ";
cout<<endl;
}
int main()
{
list a;
int aLength;
while (1)
{
a.inser();
a.output();
aLength=a.LengthOut();
cout<<"链表a的长度为:"<<aLength<<endl<<endl;
}
return 0;
}
————————————————————————————————————————
/*算法2.20*/
int list::inser() //在链表的第i个元素之前插入元素e
{
int e, i;
p=head;
cout<<"e:";
cin>>e;
cout<<"i:";
cin>>i;
s=new node(); //动态分配新节点
s->date=e;
if(Length==0) //当链表为空时无论在哪插入都视为头结点
{ head=s;; ++Length; return Length;}
else if(i<=Length) //判断插入位置是否合理
{ for(int j=1;j<=Length;++j)
{
if(i==1) //在第一位插入时 新插入的节点作为新的头结点
{ head=s; s->next=p; ++Length; return Length;break;}
if(j==i-1)
{
temp=p->next;
p->next=s;
s->next=temp;
++Length;
return Length;
break;
}//if
p=p->next;
}//for
}//if
else
cout<<"ERROR"<<endl;
}

该程序使用C++编写,实现了在带头结点的单链表中,在第i个元素之前插入新元素e的功能。首先通过输入获取要插入的元素值e和位置i,然后动态创建新节点并进行插入操作。如果链表为空,则新节点成为头结点;如果插入位置合理,遍历链表找到相应位置完成插入;否则输出错误信息。

2009

被折叠的 条评论
为什么被折叠?



