很不习惯作者在书中“鲁棒性”这个叫法,不伦不类,直接称健壮性多好,简单明了。
#include <iostream>
using namespace std;
struct Node{
int data;
Node* next;
};
class List{
private:
int N;
public:
Node* first;
List(){
N=0;
first=NULL;
last=NULL;
}
int size() { return N; }
bool isEmpty() { return first==NULL; }
//从链表尾插入
void append(int val){
Node *node=new Node();
node->data=val;
node->next=NULL;
if(isEmpty()) first=node;
else{
Node* p=first;
while(p->next) p=p->next;
p->next=node;
}
N++;
}
//从链表头插入
void push(int val){
Node* oldfirst=first;
first=new Node();
first->data=val;
first->next=oldfirst;
N++;
}
void print(){
Node* p=first;
while(p){
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
};
Node* Merge(Node *f1,Node *f2){
if( f1==NULL) return f2;
if( f2==NULL) return f1;
Node* mfirst=NULL;
if(f1->data<=f2->data){
mfirst=f1;
mfirst->next=Merge(f1->next,f2);
}
else{
mfirst=f2;
mfirst->next=Merge(f1,f2->next);
}
return mfirst;
}
int main(){
List *list1=new List();
List *list2=new List();
/*for(int i=10;i>=1;i--){
if(i%2==0){
list1->push(i);
}
else{
list2->push(i);
}
}*/
for(int i=1;i<=10;i++){
if(i%2==0){
list1->append(i);
}
else list2->append(i);
}
list1->print();
list2->print();
Node *p=Merge(list1->first,list2->first);
while(p){
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
return 0;
}
原文地址:http://blog.csdn.net/dutsoft/article/details/26744967