剑指offer刷题之c++实现的合并两个有序的链表
2015-08-08 12:16
609 查看
#include "myHead.h" #include "allListNode.h" /* 输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。 */ ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { //简化代码 // if(pHead1 == NULL&& pHead2==NULL) // return NULL; // else if(pHead1==NULL) { return pHead2; } else if(pHead2==NULL){ return pHead1; } ListNode* p,*q,*head; q = NULL; //简化代码 // if(pHead1 != NULL&& pHead2!=NULL){ while(pHead1 != NULL&& pHead2!=NULL){ if(pHead1->val <= pHead2->val){ p = (ListNode *)malloc(sizeof(ListNode)); p->val = pHead1->val; if(q==NULL){ q = p; head = q; cout<<"a"<<q->val<<" "; } else { q->next = p; q = q->next; cout<<"b "<<q->val<<" "; } pHead1 = pHead1->next; } else{ p = (ListNode *)malloc(sizeof(ListNode)); p->val = pHead2->val; if(q==NULL){ q = p; head = q; cout<<"c "<<q->val<<" "; } else { q->next = p; q = q->next; cout<<"d "<<q->val<<" "; } pHead2 = pHead2->next; } } if(pHead1 != NULL){ q->next = pHead1; } else{ q->next = pHead2; } // } return head; } int main(){ int a[]={2,4,5}; int b[] = {1,2,4,6}; int alen = sizeof(a)/sizeof(int); int blen = sizeof(b)/sizeof(int); ListNode *h1,*h2,*h; h1 = createListNode(a,alen); h2 = createListNode(b,blen); cout<<"h1: "; printListNode(h1); cout<<endl<<"h2: "; printListNode(h2); h=Merge(h1,h2); cout<<endl<<"h: "; printListNode(h); return 1; }
相关文章推荐
- 剑指offer刷题之c++实现的替换空格
- 剑指offer刷题之c++实现的求链表中倒数第k个值
- C++数组
- Leetcode -- Roman to Integer
- C++设计模式——单例模式
- 用最小最大的两个数交换首尾两数
- Caesar cipher
- c++ stl string char* 向 string 转换的问题
- C/C++程序基础
- C++静态库和动态库
- 分数相加减的代码(c++)
- c++自定义string类
- 牛客网(搜狗2015 C++工程师笔试题)
- [C++11 并发编程] 04 - 动态选择并发线程的数量
- C++连接mysql数据库的两种方法
- 【C++基础之一】C++ 虚函数表解析
- C/C++(链表应用)笔记——使用链表进行多项式的合并
- C++ 虚函数实现多态浅析
- C++面向对象--类
- C++中如何控制输出的格式