已知有两个有序的单链表head1和head2。分别使用递归方法和非递归的方法合并成一个有序的单链表。
1:递归方法。
假设两个链表:1->3->5;2->4->6.
递归的步骤如下:
(1) 比较链表一和链表2的第一个数据节点,由于1<2,因此将结果链表中的表头节点指向链表1中的第一个节点,即数据1所在节点。
(2) 对剩余的链表1和链表2再调用(1)过程,比较得到结果链表的第2个节点,即2与3比较得到2。此时合并的链表节点为1->2.
(3) 递归直到两个链表的节点都被加到结果链表中。
实现的主要函数:
Node *MergeRecursive(Node *head1,Node *head2)
{
Node *head=NULL;
if(head1==NULL)
return head2;
if(head2==NULL)
return head1;
if(head1->data < head2->data)
{
head=head1;
head->next=MergeRecursive(head1->next,head2);
}
else
{
head=head2;
head->next=MergeRecursive(head1,head2->next);
}
return head;
}
2:非递归方法。
选取两个链表中长度最短的一个链表,将最短的链表中的元素一次插入到最长链表中即可。
Node* Insert_node(Node* head,Node* item)
{
Node *p=head;
Node *q=NULL;//始终指向p之前的节点
while(p->data < item->data && p!=NULL)
{
q=p;
p=p->next;
}
if(p==head)//item->data<p-data;//插入到原头结点之前
{
item->next=p;
return item;
}
q->next=item;//插入到q与p之间
item->next=p;
return head;
}
int length(Node *head)
{
Node *p=head->next;
int len=0;
if(head->next==NULL)
return 0;
while(p!=NULL)
{
len++;
p=p->next;
}
return len;
}
Node *merge(Node *head1,Node *head2)
{
Node *head=NULL;//合并后的头指针;
Node *p=NULL;
Node *nextP=NULL;//指向p之后
if(head1==NULL)
return head2;
if(head2==NULL)
return head1;
if(length(head1) > length(head2))//选取较短的链表
{
head=head1;
p=head2;
}
else if(length(head1) == length(head2))
{
head=head2;
p=head1;
}
else
{
head=head2;
p=head1;
}
while(p!=NULL)
{
nextP=p->next;
head=Insert_node(head,p);
p=nextP;
}
return head;
}
下面是非递归方法的测试程序:
int main()
{
Node *head1=NULL,*head2=NULL;
Node *head=NULL;
cout<<"create 1th list : "<<endl;
head1=create();
cout<<"create 2th list : "<<endl;
head2=create();
cout<<"print the data of 1th list is: "<<endl;
print (head1);
cout<<endl;
cout<<"print the data of 2th list is: "<<endl;
print (head2);
cout<<endl;
cout<<"print the data of Merge list is: "<<endl;
// head=MergeRecursive(head1,head2);//递归法合并两个链表
head=merge(head1,head2);//非递归方法合并两个链表
print(head->next);
return 0;
}
输出结果如下:
采用递归的方法,输出结果与上面的一样,,此处就不在加以说明。
实现有序单链表的合并,完整代码git@code.csdn.net:snippets/2431552.git或者https://code.csdn.net/snippets/2431552.git