一、问题:合并两个有序单链表,合并后的单链表依然有序。
二、分析:
1.有如下两个有序链表str1和str2
2.合并后的新链表的头结点定义为newpHead,采用摘结点法:
三、代码实现(c语言)
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;
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。