您的位置:首页 > 职场人生

面试题---两个有序单链表的合并

2017-11-04 10:42 393 查看
#include <iostream>
using namespace std;

struct node{
int value;
struct node *next;
};

struct node *head1;
struct node *head2;

void insert(struct node * &head,int value)
{
if(head == NULL)
{
head = new struct node;
head->value = value;
head->next = NULL;
return;
}

struct node *p = new struct node;
p->value = value;
p->next = NULL;

struct node *q = head;
while(q->next != NULL)
{
q = q->next;
}

q->next = p;

}

struct node *merge(struct node *head1,struct node *head2)
{

if(head1 == NULL)
return head2;
if(head2 == NULL)
return head1;

struct node *head = NULL;
if(head1->value > head2->value)
{
head = head2;
head->next = merge(head1,head2->next);
}
else
{
head = head1;
head->next = merge(head1->next,head2);
}
return head;
}

void print(struct node *head)
{
struct node *p = head;
while(p != NULL)
{
cout<<p->value<<"  ";
p = p->next;
}
}

int main()
{
head1 = NULL;
head2 = NULL;

insert(head1,1);
if(head1 != NULL)
cout<<"确实已经赋值了呀!\n";
insert(head1,3);
insert(head1,5);
insert(head1,9);
insert(head1,11);
insert(head1,16);
insert(head1,18);
insert(head2,6);
insert(head2,10);
insert(head2,12);
insert(head2,13);
insert(head2,15);
insert(head2,18);
cout<<"链表1:\n";
print(head1);
cout<<endl;
cout<<"链表2:\n";
print(head2);
cout<<endl;
cout<<"合并后为\n";
struct node *head = NULL;
head = merge(head1,head2);
if(head != NULL)
print(head);
cout<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: