一、問(wèn)題:合并兩個(gè)有序單鏈表,合并后的單鏈表依然有序。
成都創(chuàng)新互聯(lián)公司專(zhuān)注于章貢企業(yè)網(wǎng)站建設(shè),響應(yīng)式網(wǎng)站建設(shè),購(gòu)物商城網(wǎng)站建設(shè)。章貢網(wǎng)站建設(shè)公司,為章貢等地區(qū)提供建站服務(wù)。全流程定制網(wǎng)站開(kāi)發(fā),專(zhuān)業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,成都創(chuàng)新互聯(lián)公司專(zhuān)業(yè)和態(tài)度為您提供的服務(wù)
二、分析:
1.有如下兩個(gè)有序鏈表str1和str2
2.合并后的新鏈表的頭結(jié)點(diǎn)定義為newpHead,采用摘結(jié)點(diǎn)法:
三、代碼實(shí)現(xiàn)(c語(yǔ)言)
sListNode* MergeList(sListNode* FirpHead, sListNode* SecpHead) { if(FirpHead == NULL) { return SecpHead; } if(SecpHead == NULL) { return FirpHead; } sListNode* newpHead = NULL; sListNode* firCur = FirpHead, *secCur = SecpHead; sListNode* tail = NULL; if(firCur->data < secCur->data) { newpHead = firCur; firCur = firCur->next; } else { newpHead = secCur; secCur = secCur->next; } tail = newpHead; while(firCur != NULL && secCur != NULL) { if(firCur->data < secCur->data) { tail->next = firCur; firCur = firCur->next; } else { tail->next = secCur; secCur = secCur->next; } tail = tail->next; } if(firCur == NULL) { tail->next = secCur; } if(secCur == NULL) { tail->next = firCur; } return newpHead;