1. 程式人生 > >【C++】合併兩個排序的連結串列,要求合併後仍然是有序的

【C++】合併兩個排序的連結串列,要求合併後仍然是有序的

struct ListNode {
	int m_nKey;
	ListNode m_pNext;
};
ListNode* merge(ListNode* pHead1, ListNode* pHead2) {
	if (pHead1 == NULL) {
		return pHead2;
	}
	if(pHead2 == NULL) {
		return pHead1;
	}

	ListNode* mergedList = NULL;
	if (pHead1->m_nKey < pHead2->m_nKey) {
		mergedList = pHead1;
		mergedList->m_pNext = merge(pHead1->m_pNext, pHead2);
	}
	else {
		mergedList = pHead2;
		mergedList->m_pNext = merge(pHead2->m_pNext, pHead1);
	}

	return mergedList;
}
遞迴解法,測試還是分為一般功能測試和特殊測試