合并两个排序的链表(非递归)
2014-04-25 22:33
363 查看
输入两个递增排序的链表,合并这两个链表并使新链表中的结构任然递增!
struct ListNode { int m_nValue; ListNode* m_pNext; };
ListNode* CreatList(int* data , unsigned int length) { if (!data || length<=0) { return NULL; } ListNode* pHeadNode = new ListNode(); pHeadNode->m_nValue = data[0] ; pHeadNode->m_pNext = NULL ; ListNode* pAhead = pHeadNode ; for (int i=1 ; i!= length ;i++) { ListNode* pNode = new ListNode(); pNode->m_nValue = data[i]; pNode->m_pNext = NULL; pAhead->m_pNext = pNode ; pAhead = pNode ; } pAhead = NULL ; return pHeadNode ; }
void PrintList(ListNode* pHead ) { if (!pHead) { return; } else { while (pHead->m_pNext != NULL) { cout<<pHead->m_nValue<<" "; pHead = pHead->m_pNext ; } cout<<pHead->m_nValue<<endl; } }
///////////////////合并两个排序的链表//////////////////// ListNode* Merge(ListNode* pHead1 ,ListNode* pHead2) { if (!pHead1) return pHead2; if (!pHead2) return pHead1; if (!pHead1 && !pHead2) return NULL ; ListNode* pHead = NULL ; ListNode* pNext = NULL; ListNode* pNode = NULL ; if (pHead1->m_nValue <= pHead2->m_nValue) { pHead = pHead1 ; pNode = pHead2 ; }else { pHead = pHead2 ; pNode = pHead1 ; } ListNode* pMergedHead = pHead ; while(pNode != NULL) { while((pHead->m_pNext !=NULL) && (pHead->m_pNext->m_nValue) <= (pNode->m_nValue) ) { pHead = pHead->m_pNext ; } pNext = pHead->m_pNext ; pHead->m_pNext = pNode ; pHead = pNode ; pNode = pNext ; } return pMergedHead ; }
int main() { int iv1[] = {1,3,7,7,9}; int iv2[] = {0,2,4,6,10}; ListNode* pHead1 = CreatList(iv1,5); ListNode* pHead2 = CreatList(iv2,5); PrintList(pHead1); PrintList(pHead2); ListNode* pMergedHead = Merge(pHead1,pHead2); cout<<"合并后:"; PrintList(pMergedHead); delete pMergedHead ; system("pause"); return 0; }
相关文章推荐
- litcode 合并两个排序链表 递归求解
- 剑指Offer 面试题25:合并两个排序的链表(递归+非递归) Java代码实现
- 合并两个已排序的链表(递归方法实现)
- 剑指Offer面试题16反转链表(递归和非递归),面试题17合并两个排序的链表(递归)
- 剑指offer——面试题17:合并两个排序的链表(非递归方法和递归方法)
- 面试之路(29)-合并两个排序的链表(递归和非递归)
- 面试之路(29)-合并两个排序的链表(递归和非递归)
- 剑指offer面试题25:合并两个排序的链表(c++ 递归+非递归)
- 链表——(循环和递归)合并两个排序链表
- 面试之路(29)-合并两个排序的链表(递归和非递归)
- 合并两个排序的链表---递归实现
- 面试之路(29)-合并两个排序的链表(递归和非递归)
- 【数据结构】单链表—合并两个排序链表 — 递归
- 合并两个排序链表--迭代和递归分别实现
- Language 晓彤 蒋 165. 合并两个排序链表 拼接,递归,新建
- 合并两个排序的链表(非递归)
- lintcode-合并两个排序链表
- 面试题17 合并两个排序链表
- 合并两个已经排序好的链表
- 剑指offer-17:合并两个排序的链表