您的位置:首页 > 其它

有序链表的合并(递归实现)

2010-07-21 16:09 369 查看
#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;
}
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息