面试题17:合并两个排序的链表
题目:输入两个递增排序的链表,合并这两个链表并使新链表中的结点仍然使按照递增排序的。例如:
链表1: 1->3->5->7
链表2:2->4->6->8
链表3:1->2->3->4->5->6->7->8
struct ListNode
{
int m_nKey;
ListNode *m_pNext;
};
void Show(ListNode *head)
{
for(ListNode *p=head;p!=NULL;p=p->m_pNext)
{
cout<<p->m_nKey<<ends;
}
cout<<endl;
}
//1、用递归实现 //插入后有重复元素
ListNode *Merge1(ListNode *head1,ListNode *head2)
{
if(head1 == NULL)
return head2;
else if(head2 == NULL)
return head1;
ListNode *head;
if(head1->m_nKey < head2->m_nKey)
{
head = head1;
head->m_pNext = Merge1(head1->m_pNext,head2);
}
else
{
head = head2;
head->m_pNext = Merge1(head1,head2->m_pNext);
}
return head;
}
int main()
{
ListNode *head1 = NULL;
ListNode *head2 = NULL;
for(int i=0;i<5;i++)
{
InsertTail(&head1,i+1);
}
for(int i=0;i<5;i++)
{
InsertTail(&head2,i+3);
}
cout<<"递增链表1:";
Show(head1);
cout<<"递增链表2:";
Show(head2);
cout<<"合并后的链表:";
ListNode *head = Merge1(head1,head2);
Show(head);
}
//2、用递归实现 //插入后没有重复元素
ListNode *Merge(ListNode *head1,ListNode *head2)
{
if(head1 == NULL)
return head2;
else if(head2 == NULL)
return head1;
ListNode *head;
if(head1->m_nKey < head2->m_nKey)//把两个链表中小的元素插入head
{
head = head1;
head->m_pNext = Merge(head1->m_pNext,head2);
}
else if(head1->m_nKey == head2->m_nKey)//相同元素插入一次
{
head = head1;
head->m_pNext = Merge(head1->m_pNext,head2->m_pNext);
}
else
{
head = head2;
head->m_pNext = Merge(head1,head2->m_pNext);
}
return head;
}
int main()
{
ListNode *head1 = NULL;
ListNode *head2 = NULL;
for(int i=0;i<5;i++)
{
InsertTail(&head1,i+1);
}
for(int i=0;i<5;i++)
{
InsertTail(&head2,i+3);
}
cout<<"递增链表1:";
Show(head1);
cout<<"递增链表2:";
Show(head2);
cout<<"合并后的链表:";
ListNode *head = Merge(head1,head2);
Show(head);
}
//3、非递归实现 插入后没有重复元素
void InsertTail(ListNode **head,int key)
{
ListNode *newnode = new ListNode();
newnode->m_nKey = key;
newnode->m_pNext = NULL;
if(*head == NULL)
{
*head = newnode;
}
else
{
ListNode *p = *head;
while(p->m_pNext != NULL)
p = p->m_pNext;
p->m_pNext = newnode;
}
}
ListNode* Merge(ListNode *head1, ListNode *head2)
{
if(head1==NULL && head2==NULL)
return NULL;
if(head1 == NULL && head2!=NULL)
return head2;
else if(head2==NULL && head1!=NULL)
return head1;
ListNode *head = NULL;
ListNode *p1 = head1;
ListNode *p2 = head2;
while(p1!=NULL && p2!=NULL)//p1,p2都不为空
{
if(p1->m_nKey < p2->m_nKey)
{
InsertTail(&head,p1->m_nKey);
p1 = p1->m_pNext;
}
else if(p1->m_nKey == p2->m_nKey)
{
InsertTail(&head,p1->m_nKey);
p1 = p1->m_pNext;
p2 = p2->m_pNext;
}
else
{
InsertTail(&head,p2->m_nKey);
p2 = p2->m_pNext;
}
}
while(p1 != NULL)//p2遍历完,把p1剩余的元素接到head后面
{
InsertTail(&head,p1->m_nKey);
p1 = p1->m_pNext;
}
while(p2 !=NULL)//p1遍历完,把p2剩余的元素接到head后面
{
InsertTail(&head,p2->m_nKey);
p2 = p2->m_pNext;
}
return head;
}
int main()
{
ListNode *head1 = NULL;
ListNode *head2 = NULL;
for(int i=0;i<5;i++)
{
InsertTail(&head1,i+1);
}
for(int i=0;i<5;i++)
{
InsertTail(&head2,i+3);
}
cout<<"递增链表1:";
Show(head1);
cout<<"递增链表2:";
Show(head2);
cout<<"合并后的链表:";
ListNode *head = Merge(head1,head2);
Show(head);
}