(2)已知兩個鏈表head1 和head2 各自有序,請把它們合并成一個鏈表依然有序。(保留所有結(jié)點,即便大小相同)
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)已知兩個鏈表head1 和head2各自有序,請把它們合并成一個鏈表依然有序,這次要求用遞歸方法進行。 (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 ;
}
唯學網(wǎng)是一個大型的教育考試培訓平臺,更多Java認證考試報名,Java認證考試準考證和成績查詢等相關考試信息,請關注唯學網(wǎng)職業(yè)資格欄目IT認證考試培訓頻道。小編在此預祝每一位參加Java認證考試的考生都能夠順利通過,早日實現(xiàn)自己的夢想。
|
|
||
|
|