坚持每月一篇
list的构造就不重复了,详见链表的构造
//递归方式
PNode Merge(PNode head1, PNode head2)
{
PNode newhead = NULL;
if(NULL == head1) {
return head2;
}
else if (NULL == head2) {
return head1;
}
if(head1->data <= head2->data) {
newhead = head1;
newhead->next = Merge(head1->next, head2);
}
else {
newhead = head2;
newhead->next = Merge(head1, head2->next);
}
return newhead;
}
//非递归方式
PNode Merge2(PNode head1, PNode head2)
{
PNode head = NULL;
//先找到两个表中较小的头结点为新的头结点
if (head1->data <= head2->data){
head = head1;
head1 = head1->next;
}
else {
head = head2;
head2 = head2->next;
}
//需要记录一下头结点的位置,不能用head直接操作,否则会丢失这个新链表
PNode cur = head;
while (NULL != head1 && NULL != head2) {
if(head1->data <= head2->data) {
cur->next = head1;
cur = head1;
head1 = head1->next;
}
else {
cur->next = head2;
cur = head2;
head2 = head2->next;
}
}
// 走到这里的条件是两个链表中一定有一个遍历完
// 如果剩下的链表还没遍历完,则把链表接到后面
if (NULL != head1) {
cur->next = head1;
}
if (NULL != head2) {
cur->next = head2;
}
return head;
}
main.c
PNode head1 = initList();
PNode head2 = initList();
PNode node1 = makenode(1);
PNode node2 = makenode(3);
PNode node3 = makenode(5);
PNode node4 = makenode(2);
PNode node5 = makenode(4);
PNode node6 = makenode(6);
insert(head1,head1,node1);
insert(head1,node1,node2);
insert(head1,node2,node3);
insert(head2,head2,node4);
insert(head2,node4,node5);
insert(head2,node5,node6);
PNode newhead = Merge(head1, head2);
while(NULL != newhead) {
printf("newhead data is %d\n", newhead->data);
newhead = newhead->next;
}
运行结果
newhead data is 0
newhead data is 0
newhead data is 1
newhead data is 2
newhead data is 3
newhead data is 4
newhead data is 5
newhead data is 6