本文共 1966 字,大约阅读时间需要 6 分钟。
#include <cstdlib>#include <iostream>#include <vector>#include <ctime>#include <algorithm>using namespace std;typedef struct _NODE{ int data; struct _NODE *next; _NODE(int val): data(val), next(NULL){} friend ostream& operator <<(ostream &os, const _NODE &nod) { return os << nod.data << "->"; }}NODE, *PTRNODE;void createList(PTRNODE &head, int num){ vector<int> val; srand((unsigned)time(NULL)); for(int i=0; i<num; i++) val.push_back(rand() % 100); sort(val.begin(), val.end()); PTRNODE curNode = NULL; for(int i=0; i<num; i++) { if(head == NULL) { head = new NODE(val[i]); curNode = head; } else { PTRNODE newNode = new NODE(val[i]); curNode->next = newNode; curNode = curNode->next; } }}PTRNODE mergeList(PTRNODE list1, PTRNODE list2){ PTRNODE head = NULL; if(list1 == NULL) return list2; if(list2 == NULL) return list1; if(list1->data < list2->data) { head = list1; head->next = mergeList(list1->next, list2); } else { head = list2; head->next = mergeList(list1, list2->next); } return head;}void display(PTRNODE head){ if(head == NULL) { cout << "empty list" << endl; return; } PTRNODE curNode = head; while(curNode != NULL) { cout << *curNode; curNode = curNode->next; } cout << endl;}int main(int argc, char *argv[]){ PTRNODE list1 = NULL, list2 = NULL; createList(list1, 10); createList(list2, 20); cout << "list1 is: " << endl; display(list1); cout << "list2 is: " << endl; display(list2); PTRNODE result = mergeList(list1, list2); cout << "merge result is: " << endl; display(result); system("PAUSE"); return EXIT_SUCCESS;}
转载地址:http://hfkqb.baihongyu.com/