最近复习到这个知识点,打一打码。
#include <iostream>
using namespace std;
struct DList{
int value;
DList *l;
DList *r;
};
DList* createDList(){
int x;
DList*head=new DList;
head->value=0;
head->l=NULL;
head->r=NULL;
DList*ptemp,*pnew;
ptemp=head;
while(cin>>x&&x!=0){
pnew=new DList;
pnew->value=x;
pnew->r=NULL;
pnew->l=ptemp;
ptemp->r=pnew;
ptemp=pnew;
}
return head;
}
void insertNode(DList *&head){
//插入多少号就是代替多少号的原来的位置,原来的依次“后移 ”
cout<<"请输入要插入的位置还有插入的值" <<endl;
int position;
cin>>position;
DList*p=head;
DList*pnext=p->r;
while(--position){
p=pnext;
pnext=pnext->r;
}
//插入。
DList*ptemp=new DList;
cin>>ptemp->value;
ptemp->l=p;
ptemp->r=pnext;
p->r=ptemp;
pnext->l=ptemp;
}
void deleteNode(DList *&head){
cout<<"请输入删除的值"<<endl;
int x;
cin>>x;
DList*p=head;
DList*q=head->r;
while(q!=NULL&&q->value!=x){
p=q;
q=q->r;
}
if(q==NULL){
cout<<"没找到对应元素,删除失败!"<<endl;
}
else{
//若q为最后一个节点,那么直接删除它。
if(q->r==NULL) {
p->r=NULL;
delete q;
}
else{
q->r->l=p;
p->r=q->r;
delete q;
}
}
}
void travel(DList*head){
DList*p=head->r;
while(p!=NULL){
cout<<p->value<<" ";
p=p->r;
}
cout<<endl;
}
int main(){
DList*head=createDList();
travel(head);
insertNode(head);
travel(head);
deleteNode(head);
travel(head);
return 0;
}

3138

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



