1. 程式人生 > >C++實現雙向連結串列的建立,插入,修改,刪除

C++實現雙向連結串列的建立,插入,修改,刪除

#include<iostream>
#include<string>
using namespace std;
struct Node
{
int value;
Node* pre;
Node* next;
};
class Double_list
{
private:
Node*head;
public:
Double_list()
{
head=NULL;
}
void Create()
{
int value;
string str;
while(1)
{
cout<<"Do you want to re-Enter element (Yes(Y)/No(N)) ";
cin>>str;

if(str=="Y"||str=="yes"||str=="y")
{
cout<<"Please input the value ";
cin>>value; 
if(head==NULL)
{
head=new Node;
head->value=value;
head->pre=NULL;
head->next=NULL;
}
else
{
Node* p=head;
while(p!=NULL&&p->next!=NULL)
p=p->next;
if(p!=NULL)
{
p->next=new Node;
p->next->value=value;
p->next->pre=p;
p->next->next=NULL;
}
}
}
else
{
cout<<"please input the right value,go ahead the following process"<<endl;
break;
}
}
}
void insert_node()
{
if(head==NULL)
{
cout<<"This is a empty double-list,insert failed!"<<endl;
return ;
}
int value1,value2;
cout<<"Please input the value of insert pos ";
cin>>value1;
cout<<"Please input the value to be inserted";
cin>>value2;
Node*p1,*p2;
p1=head;
/*假設插入的節點是頭結點*/
if(head->value==value1)
{
Node*newNode=new Node;
newNode->value=value2;
newNode->next=head;
head->pre=newNode;
newNode->pre=NULL;
head=newNode;
return;
}
while(p1!=NULL&&p1->next!=NULL&&p1->next->value!=value1)
{
p1=p1->next;
}
if(p1!=NULL&&p1->next!=NULL)
{
p2=p1->next;
Node*p3=new Node;
p3->value=value2;
p3->pre=p1;
p1->next=p3;
p3->next=p2;


}
else
{
cout<<"can't find the refering node,inserting failed!"<<endl;
return ;
}
}
void Delete_node()
{
Node*p1,*p2;


if(head==NULL)
{
cout<<"remove node from an empty double-list failed!"<<endl;
return ;
}
else
{
int value;
cout<<"please input the value of the node to be deleted"<<endl;
cin>>value;
p1=head;
if(head->value==value)// 假如刪除的是頭結點
{
Node*temp=head;
head=head->next;
head->pre=NULL;
delete temp;
p1=NULL;
return ;
}


while(p1!=NULL&&p1->next!=NULL&&p1->next->value!=value)
{
p1=p1->next;
}
if(p1!=NULL&&p1->next!=NULL)
{
p2=p1->next;
p1->next=p2->next;
p2->next->pre=p1;
}
else
{
cout<<"Can't find the value"<<endl;
}
}
}
void Modify_node()
{
int value1,value2;
cout<<"Please input the value in the list to be modified"<<endl;
cin>>value1;
cout<<"please input the modified value"<<endl;
cin>>value2;
Node* p1=head,*p2;
while(p1!=NULL&&p1->value!=value1)
{
p1=p1->next;
}
if(p1!=NULL)
{
p1->value=value2;
}
else
{
cout<<"can't find the value"<<endl;
}
}
void print_begin_to_end()
{
Node*p=head;
while(p!=NULL)
{
cout<<p->value<<" ";
p=p->next;
}
cout<<endl;
}
void print_end_to_begin()
{
Node*p=head;
while(p->next!=NULL)
{
p=p->next;
}
while(p!=NULL)
{
cout<<p->value<<" ";
p=p->pre;
}
cout<<endl;
}
};




int main()
{
Double_list  L;
L.Create();
L.print_begin_to_end();
L.print_end_to_begin();

L.Modify_node();
L.print_begin_to_end();
L.print_end_to_begin();


L.insert_node();
L.print_begin_to_end();
L.print_end_to_begin();


L.Delete_node();
L.print_begin_to_end();
L.print_end_to_begin();


return 0;

}



經除錯,可執行