分为正向序号插入数值和逆向序号插入数值
正向code:
#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct Dulnode
{
int data;
struct Dulnode *prior,*next;
}DulNode;
DulNode *Input(int n)
{
DulNode *head,*p,*q;
head=p=(DulNode*)malloc(sizeof(DulNode));
p->next=head;
head->prior=p;
for(int i=0;i<n;i++)
{
int data;
cin>>data;
q=(DulNode*)malloc(sizeof(DulNode));
q->data=data;
q->next=p->next;
q->prior=p;
p->next=q;
head->prior=q;
p=q;
}
return head;
}
void ShowPos(DulNode *L)
{
DulNode *p;
p=L->next;
while(p!=L)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
int InsertPos(DulNode *L,int id,int num)
{
DulNode *p,*s;
p=L;
int mark=1;
int pos=0;
while(p!=L||mark)
{
if(pos==id-1)
{
s=(DulNode*)malloc(sizeof(DulNode));
s->data=num;
s->next=p->next;
p->next->prior=s;
p->next=s;
s->prior=p;
return 1;
}
p=p->next;
pos++;
mark=0;
}
if(pos!=id) return 0;
}
int main()
{
int n;
while(cin>>n)
{
DulNode *head=Input(n);
cout<<"正向遍历:";
ShowPos(head);
while(1)
{
int id,num;
cout<<"输入插入的序号:";
cin>>id;
cout<<"输入插入的数据:";
cin>>num;
if(InsertPos(head,id,num))
{
cout<<"正向序号:";
ShowPos(head);
//cout<<"逆向序号:";
//InsertNeg(head,id,num);
//ShowPos(head);
}
else cout<<"序号无效"<<endl;
}
}
return 0;
}
逆向code:
#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct Dulnode
{
int data;
struct Dulnode *prior,*next;
}DulNode;
DulNode *Input(int n)
{
DulNode *head,*p,*q;
head=p=(DulNode*)malloc(sizeof(DulNode));
p->next=head;
head->prior=p;
for(int i=0;i<n;i++)
{
int data;
cin>>data;
q=(DulNode*)malloc(sizeof(DulNode));
q->data=data;
q->next=p->next;
q->prior=p;
p->next=q;
head->prior=q;
p=q;
}
return head;
}
void ShowNeg(DulNode *L)
{
DulNode *p;
p=L->prior;
while(p!=L)
{
cout<<p->data<<" ";
p=p->prior;
}
cout<<endl;
}
void ShowPos(DulNode *L)
{
DulNode *p;
p=L->next;
while(p!=L)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
int InsertNeg(DulNode *L,int id,int num)
{
DulNode *p,*s;
p=L;
int mark=1;
int pos=0;
while(p!=L||mark)
{
if(pos==id-1)
{
s=(DulNode*)malloc(sizeof(DulNode));
s->data=num;
s->next=p->next;
p->next->prior=s;
p->next=s;
s->prior=p;
return 1;
}
p=p->prior;
pos++;
mark=0;
}
if(pos!=id) return 0;
}
int main()
{
int n;
while(cin>>n)
{
DulNode *head=Input(n);
cout<<"逆向遍历:";
ShowNeg(head);
while(1)
{
int id,num;
cout<<"输入插入的序号:";
cin>>id;
cout<<"输入插入的数据:";
cin>>num;
if(InsertNeg(head,id,num))
{
cout<<"逆向序号:";
ShowPos(head);
}
else cout<<"序号无效"<<endl;
}
}
return 0;
}