您的位置:首页 > 编程语言 > C语言/C++

链表的有序合并相关_C++实现

2011-09-13 19:41 507 查看
构造两个链表

将链表2有序合并到链表1

增加功能使其能删除链表中重复的元素

"head.h"

#include<iostream>
using namespace std;

class NODE
{
public:
NODE();
int num;
NODE *next;
};

NODE::NODE()
{
num=0;
next=NULL;
}

class DATA
{
public:
DATA();
void Constructor();
void Merge();
void Print();
void Process();
private:
NODE *head1,*head2,*p,*pr,*keep;
bool first;
};

DATA::DATA()
{
pr=keep=head1=head2=p=NULL;
first=true;
}

void DATA::Constructor()
{
if(first)
cout<<"Constructor 1 called !"<<endl;
else
cout<<"Constructor 2 called !"<<endl;
cout<<"How Many Numbers Do You Want To Enter ?"<<endl<<endl;
int nnum,input;
cin>>nnum;
if(nnum!=0)
{
p=new NODE;
cin>>input;
p->num=input;
if(first)
head1=p;
else
head2=p;
nnum--;
}
while(nnum--)
{
p->next=new NODE;
p=p->next;
cin>>input;
p->num=input;
}
p->next=NULL;
first=!first;
}

void DATA::Merge()
{
cout<<"Merge called !"<<endl<<endl;
pr=p=head1;
if(head1->num>head2->num)
{
keep=head2->next;
head1=head2;
head2->next=p;
pr=head2;
head2=keep;
}
while(1)
{
while(p!=NULL&&p->num<=head2->num)
{
pr=p;
p=p->next;
}
if(p==NULL)
{
pr->next=head2;
return;
}
else
{
keep=head2->next;
pr->next=head2;
head2->next=p;
head2=keep;
pr=pr->next;
if(head2==NULL)
return;
}
}
}

void DATA::Print()
{
cout<<"Print called !"<<endl<<endl;
p=head1;
while(p!=NULL)
{
cout<<p->num<<endl;
p=p->next;
}
cout<<endl;
}

void DATA::Process()
{
p=pr=head1;
p=p->next;
while(p!=NULL)
{
if(p->num==pr->num)
{
pr->next=p->next;
delete p;
p=pr->next;
}
else
{
pr=p;
p=p->next;
}
}
}


"main.cpp"

#include<iostream>
#include"head.h"
using namespace std;

int main()
{
DATA data;
data.Constructor();
data.Constructor();
data.Merge();
//	data.Process();
data.Print();
system("pause");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: