题目:合并两个有序链表。
递归实现参考代码:
LinkList *Merge(LinkList *pHead1,LinkList *pHead2) { if(pHead1==NULL) { return pHead2; } else if(pHead2==NULL) { return pHead1; } LinkList *pNewMergeHead=NULL; if((pHead1->data) < (pHead2->data)) { pNewMergeHead=pHead1; pNewMergeHead->next=Merge(pHead1->next,pHead2); } else { pNewMergeHead=pHead2; pNewMergeHead->next=Merge(pHead1,pHead2->next); } return pNewMergeHead; }
非递归实现参考代码:
pLinkNode Merge(pList L1,pList L2)//合并两个有序链表 { pLinkNode newHead=NULL; if(L1==L2) { return L1;//相等时返回任意值均可 } if( (L1==NULL) && (L2!=NULL) ) { return L2; } if( (L1!=NULL) && (L2==NULL) ) { return L1; } if(L1->data < L2->data) { newHead=L1; L1=L1->next; } else { newHead=L2; L2=L2->next; } pLinkNode cur=newHead; while(L1 && L2) { if(L1->data < L2->data) { cur->next=L1; L1=L1->next; } else { cur->next=L2; L2=L2->next; } cur=cur->next; } if(L1)//L2或L1为空后 { cur->next=L1; } else { cur->next=L2; } return newHead; }