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

构造两个链表

将链表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"); }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值