堅持每月一篇
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