C++面试题细解

1.已知两个链表head1和head2各自有序,请把它们合并成一个链表依然有序。(保留所有节点,即便大小相同)

typedef struct Node
{
int data;
struct Node *next;
}Node, *PNode;


Node *link(Node *head1,Node *head2)
{
if(head1 == NULL)
return head2;
if(head2 == NULL)
return head1;
Node *head = NULL;
Node *temp1 = NULL;
Node *temp2 = NULL;
if(head1->data < head2->data)//升序排列
{
head = head1;
temp1 = head1->next;
temp2 = head2;
}
else
{
head = head2;
temp1 = head1;
temp2 = head2->next;
}
Node *temp3 = head;
while(temp1 != NULL && temp2 != NULL)
{
if(temp1->data < temp2->data)
{
temp3->next = temp1;
temp3 = temp3->next;
temp1 = temp1->next;
}
else
{
temp3->next = temp2;
temp3 = temp3->next;
temp2 =temp2->next;
}
}
if(temp1 == NULL)
temp3->next = temp2;
if(temp2 == NULL)
temp3->next = temp1;
return head;
}
int main()
{
/* int a[5]={'1','0','2'};
int *p;
p = a;
printf("%d\n",sizeof(a));
*/
Node *head1 = NULL;
Node *head2 = NULL;
Node *p1 = NULL;
Node *p2 = NULL;
Node *p3 = NULL;
head1 = (Node *)malloc(sizeof(struct Node));
head2 = (Node *)malloc(sizeof(struct Node));
p1 = (Node *)malloc(sizeof(struct Node));
p2 = (Node *)malloc(sizeof(struct Node));


head1->data = 1;
p1->data =2;
p1->next = NULL;
head1->next = p1;


head2->data = 3;
p2->data = 4;
p2->next = NULL;
head2->next = p2;


p3 = link(head1, head2);

Node* p = NULL;
Node* pfree = NULL;
p = p3;
int i=0;
for(i=0;p != NULL;i++)
{
printf("%d:%d\n",i,p->data);
pfree= p;
p = p->next;
free(pfree);
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值