用C++:编写将两个已知的有序链表合并为一个有序链表的函数。

2024-12-20 20:45:58
推荐回答(2个)
回答1:

node* merge( node* a, node* b) {
node* head=NULL, tail=NULL, cur_a, cur_b;
cur_a = a;
cur_b = b;
while(cur_a!=NULL&&cur_b!=NULL) {
if (head==NULL) {
if ( (cur_a->data)>(cur_b->data) ) {
head = cur_a;
cur_a = cur_a->next;
} else {
head = cur_b;
cur_b = cur_b->next;
}
tail = head;
}else {
if ( (cur_a->data)>(cur_b->data) ) {
tail->next = cur_a;
tail = tail->next;
cur_a = cur_a->next;

}else {
tail->next = cur_b;
tail = tail->next;
cur_b = cur_b->next;
}
}

}
if (cur_a == NULL)

tail->next = cur->b;

else
tail->next = cur->a;

return head;

}

回答2:

根据大小,指针交替移动,直到一个链表结束。将另一链表连接到尾部即可。