/*双向链表的插入与删除*/
#include<iostream>
using namespace std;struct node //双向链表的节点
{
int date;
node *next; //指向后一个节点
node *prior; //指向前一个节点
};
class list //创建链表类
{
node *head,*s,*p,*q; //head—头结点 s—新节点 p—创建链表 q—打印链表/插入元素
public:
list(){head=NULL;} //创建一个空的头结点
int InitList(); //初始化
void output(); //打印
int inser(int Length); //插入
int Delete(int Length); //删除
};
int list::InitList()
{
int x=1; //x 记录初始的表长
while (x<11) //创建一个长度为10的链表
{
s=new node(); //创建一个新的节点
s->date=x;
if(head==NULL)
{s->next=s->prior=NULL;p=head=s;}
else
{ s->date=x;
s->next=head; //循环链表与非循环的区别
s->prior=p; //将节点p作为新节点s的上一个节点
head->prior=s;
p->next=s; //将新节点s作为节点p的下一个节点
p=p->next;} //节点p后移
++x;
}
return x-1;
}
void list::output() //打印链表
{
q=head;
cout<<"linklist: ";
cout<<q->date<<" ";
q=q->next;
if(q!=NULL)
for (;q!=head;q=q->next)
cout<<q->date<<" ";
cout<<". head is "<<head->date<<endl;
}
int list::inser(int Length)
{ int y=1; // y 记录当前节点在链表中的排位
int place , elem;
node *temp; //创建一个临时节点
cout<<"请输入要插入的数据:"<<endl;
cin>>elem;
cout<<"请输入要插入的位置:"<<endl;
cin>>place;
cout<<"数据:"<<elem<<" 位置:"<<place<<endl;
if(place>Length)
{cout<<"当前链表长度为:"<<Length<<endl;return 0;}
s=new node();
s->date=elem;
for(q=head;y<Length+1; ++y)
{
if(y==place)
{
temp=q->prior; //临时节点为当前节点的前一个节点
temp->next=s;
s->prior=temp;
s->next=q;
q->prior=s;
if(place==1)
{ head=s; }
break;
}
q=q->next;
}//for
}
int list::Delete(int Length)
{
int y=1; // y 记录当前节点在链表中的排位
int elem;
node *temp1,*temp2; //创建两个临时节点
cout<<"请输入要删除的数据:"<<endl;
cin>>elem;
for(q=head;y<Length+1;++y)
{
if(q->date==elem)
{
temp1=q->prior; //临时节点1为当前节点的前一个节点
temp2=q->next; //临时节点2为当前节点的后一个节点
temp1->next=temp2;
temp2->prior=temp1;
if(head->date==elem)
{ head=head->next; }
return 0;
}
q=q->next;
}//for
cout<<"链表中没有你所输入的数据,所以无法执行删除"<<endl;
}
int main()
{
list A;
int Length=A.InitList();
cout<<Length;
A.output();
A.inser(Length);
++Length;
A.output();
A.Delete(Length);
A.output();
while(1){}
return 0;
}
————————————————————————————————————————————————————————
/*双向链表的插入—算法2.18*/
int list::inser(int Length)
{ int y=1; // y 记录当前节点在链表中的排位
int place , elem;
node *temp; //创建一个临时节点
cout<<"请输入要插入的数据:"<<endl;
cin>>elem;
cout<<"请输入要插入的位置:"<<endl;
cin>>place;
cout<<"数据:"<<elem<<" 位置:"<<place<<endl;
if(place>Length)
{cout<<"当前链表长度为:"<<Length<<endl;return 0;}
s=new node();
s->date=elem;
for(q=head;y<Length+1; ++y)
{
if(y==place)
{
temp=q->prior; //临时节点为当前节点的前一个节点
temp->next=s;
s->prior=temp;
s->next=q;
q->prior=s;
if(place==1)
{ head=s; }
break;
}
q=q->next;
}//for
}
/*双向链表的删除—算法2.19*/
int list::Delete(int Length)
{
int y=1; // y 记录当前节点在链表中的排位
int elem;
node *temp1,*temp2; //创建两个临时节点
cout<<"请输入要删除的数据:"<<endl;
cin>>elem;
for(q=head;y<Length+1;++y)
{
if(q->date==elem)
{
temp1=q->prior; //临时节点1为当前节点的前一个节点
temp2=q->next; //临时节点2为当前节点的后一个节点
temp1->next=temp2;
temp2->prior=temp1;
if(head->date==elem)
{ head=head->next; }
return 0;
}
q=q->next;
}//for
cout<<"链表中没有你所输入的数据,所以无法执行删除"<<endl;
}