标签:
合并两个有序的链表并使新链表也是有序排列。
1 ListNode* Merge(ListNode* pHead1, ListNode* pHead2) 2 { 3 if (pHead1 == NULL) 4 return pHead2; 5 else if (pHead2 == NULL) 6 return pHead1; 7 ListNode *pNewHead = NULL, *pNode1 = NULL, *pNode2 = NULL; 8 if (pHead1->m_nValue <= pHead2->m_nValue) 9 { 10 pNewHead = pHead1; 11 pNode1 = pHead1->m_pNext; 12 pNode2 = pHead2; 13 } 14 else 15 { 16 pNewHead = pHead2; 17 pNode1 = pHead1; 18 pNode2 = pHead2->m_pNext; 19 } 20 21 ListNode* pNewListLastNode = pNewHead; 22 23 while (pNode1 != NULL && pNode2 != NULL) 24 { 25 if (pNode1->m_nValue <= pNode2->m_nValue) 26 { 27 pNewListLastNode->m_pNext = pNode1; 28 pNewListLastNode = pNode1; 29 pNode1 = pNode1->m_pNext; 30 } 31 else 32 { 33 pNewListLastNode->m_pNext = pNode2; 34 pNewListLastNode = pNode2; 35 pNode2 = pNode2->m_pNext; 36 } 37 } 38 39 // 一个链表遍历完了,另一个直接链接到后面即可 40 if (pNode1 == NULL) 41 { 42 pNewListLastNode->m_pNext = pNode2; 43 } 44 else 45 { 46 pNewListLastNode->m_pNext = pNode1; 47 } 48 49 return pNewHead; 50 }
标签:
原文地址:http://www.cnblogs.com/wangjzh/p/4340900.html