数据结构 P38 算法实现 在带头结点的单链表的第i个元素插入元素e

来源:互联网 发布:sql where in 编辑:程序博客网 时间:2024/05/22 05:30

/*程序*/

#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;
}

阅读全文
1 0