合并有序链(从小到大)

#include < algorithm >
#include < iostream >
#include < random >
#include < set >
#include < time.h >
#include < vector >

using namespace std;

struct LinkNode
{
int val ;
LinkNode *next ;
};

LinkNode * makeLink ( const vector < int > & vec )
{
if (vec. empty() )
return nullptr ;

vector < int > tmp(vec. begin(), vec. end()) ;
sort(tmp. begin(), tmp. end()) ;

LinkNode *head = new LinkNode() ;
LinkNode *cur = head ;
for ( int i = 0 ; i < tmp. size() ; i ++ )
{
cur-> val = tmp[i] ;
if (i < tmp. size() - 1 )
cur-> next = new LinkNode() ;
else
cur-> next = nullptr ;
cur = cur-> next ;
}
return head ;
}

// 合并链的具体逻辑
LinkNode * mergeLink ( LinkNode * link1, LinkNode * link2 )
{
if (link1 == nullptr && link2 == nullptr )
{
return nullptr ;
}
else if (link1 == nullptr && link2 )
{
return link2 ;
}
else if (link2 == nullptr && link1 )
{
return link1 ;
}
else
{
if (link1-> val < link2-> val )
{
link1-> next = mergeLink(link2, link1-> next) ;
return link1 ;
}
else
{
link2-> next = mergeLink(link1, link2-> next) ;
return link2 ;
}
}
}

void printLink ( LinkNode * head )
{
LinkNode *tmp = head ;

while (tmp != nullptr )
{
// cout << tmp->val << endl;
tmp = tmp-> next ;
}
}

void linkToVector ( LinkNode * head, vector < int > & kvec )
{
while (head != nullptr )
{
kvec. push_back(head-> val) ;
head = head-> next ;
}
}

void RandomArray ( vector < int > & kvec, const int length )
{
if (length <= 0 )
return ;

kvec. resize(length) ;

srand (( unsigned ) time ( nullptr ));
for ( int i = 0 ; i < length ; i ++ )
{
kvec[i] = rand () % 100 ;
}
}

void test ( const int length1, const int length2 )
{
vector < int > vec1 ;
vector < int > vec2 ;
vector < int > vec3 ;
vector < int > vec4 ;

RandomArray(vec1, length1) ;
RandomArray(vec2, length2) ;

LinkNode *head1 = makeLink(vec1) ;
printLink(head1) ;
LinkNode *head2 = makeLink(vec2) ;
printLink(head2) ;

vec3. resize(vec1. size() + vec2. size()) ;
merge(vec1. begin(), vec1. end(),
vec2. begin(), vec2. end(),
vec3. begin()) ;
sort(vec3. begin(), vec3. end()) ;

LinkNode *ret = mergeLink(head1, head2) ;
printLink(ret) ;

linkToVector(ret, vec4) ;

if (vec3 != vec4 )
cout << " err " << endl ;
}

int main ()
{
srand (( unsigned ) time ( nullptr ));
const int length1 = rand () % 10 ;
const int length2 = rand () % 20 ;

int n = 0 ;
int count = 0 ;
// 输入1开始测试,输入0停止测试
while ( scanf ( " %d ", &n ) , n )
{
for ( int i = 0 ; i < 100 ; ++i )
{
test(length1,length2) ;
}
cout << ++count << endl ;
}

return 1 ;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值