(2)已知兩個(gè)鏈表head1 和head2 各自有序,請把它們合并成一個(gè)鏈表依然有序。(保留所有結(jié)點(diǎn),即便大小相同)
Node *Merge(Node *head1 , Node *head2)
{
if ( head1 == NULL)
return head2;
if ( head2 == NULL)
return head1 ;
Node *head = NULL ;
Node*p1 = NULL;
Node *p2 = NULL;
if ( head1->data < head2->data )
{
head = head1 ;
p1 = head1->next;
p2 = head2 ;
}
else
{
head = head2 ;
p2 = head2->next ;
p1 = head1 ;
}
Node *pcurrent = head ;
while ( p1 != NULL && p2 != NULL)
{
if ( p1->data <= p2->data )
{
pcurrent->next = p1;
pcurrent = p1 ;
p1 = p1->next ;
}
else
{
pcurrent->next = p2 ;
pcurrent = p2 ;
p2 = p2->next ;
}
}
if ( p1 != NULL )
pcurrent->next = p1 ;
if ( p2 != NULL )
pcurrent->next = p2 ;
return head ;
}
(3)已知兩個(gè)鏈表head1 和head2各自有序,請把它們合并成一個(gè)鏈表依然有序,這次要求用遞歸方法進(jìn)行。 (Autodesk)
答案:
Node *MergeRecursive(Node *head1 , Node *head2)
{
if ( head1 == NULL )
return head2 ;
if ( head2 == NULL)
return head1 ;
Node *head =NULL ;
if ( head1->data < head2->data )
{
head = head1 ;
head->next = MergeRecursive(head1->next,head2);
}
else
{
head = head2 ;
head->next = MergeRecursive(head1,head2->next);
}
return head ;
}
唯學(xué)網(wǎng)是一個(gè)大型的教育考試培訓(xùn)平臺,更多Java認(rèn)證考試報(bào)名,Java認(rèn)證考試準(zhǔn)考證和成績查詢等相關(guān)考試信息,請關(guān)注唯學(xué)網(wǎng)職業(yè)資格欄目IT認(rèn)證考試培訓(xùn)頻道。小編在此預(yù)祝每一位參加Java認(rèn)證考試的考生都能夠順利通過,早日實(shí)現(xiàn)自己的夢想。
|
|
||
|
|