【剑指offer 面试题17】合并两个排序的链表
2015-06-22 15:20
561 查看
思路:
比较两个链表端点值的大小,通过递归的方式排列。
测试结果:
比较两个链表端点值的大小,通过递归的方式排列。
#include <iostream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int v = 0):val(v), next(NULL){} }; ListNode *SortedListMerge(ListNode *phead1, ListNode *phead2) { if(phead1 == NULL) return phead2; else if(phead2 == NULL) return phead1; ListNode *pMergedHead = NULL; if(phead1->val < phead2->val) { pMergedHead = phead1; pMergedHead->next = SortedListMerge(phead1->next, phead2); } else { pMergedHead = phead2; pMergedHead->next = SortedListMerge(phead1, phead2->next); } return pMergedHead; } int main() { ListNode *l1 = new ListNode(1); ListNode *h1 = l1; for(int i = 3; i <= 11; i += 2) { ListNode *temp = new ListNode(i); l1->next = temp; l1 = l1->next; } ListNode *l2 = new ListNode(2); ListNode *h2 = l2; for(int i = 4; i <= 12; i += 2) { ListNode *temp = new ListNode(i); l2->next = temp; l2 = l2->next; } cout<<"List1: "; ListNode *print1 = h1; while(print1 != NULL) { cout<<print1->val<<" "; print1 = print1->next; } cout<<endl; cout<<"List2: "; ListNode *print2 = h2; while(print2 != NULL) { cout<<print2->val<<" "; print2 = print2->next; } cout<<endl; ListNode *mergeList = SortedListMerge(h1, h2); cout<<"ListMerge: "; ListNode *printlist = mergeList; while(printlist != NULL) { cout<<printlist->val<<" "; printlist = printlist->next; } cout<<endl; }
测试结果:
List1: 1 3 5 7 9 11 List2: 2 4 6 8 10 12 ListMerge: 1 2 3 4 5 6 7 8 9 10 11 12
相关文章推荐
- 伟大程序员的十大特质
- 黑马程序员----传说中的Java
- 黑马程序员JAVA笔记4--继承
- 黑马程序员----开始写Blog
- 剑指offer 面试题4
- [转]乐死我了,怎么样成为一个全栈程序员(Full Stack Developer),附我想专注的语言
- 毕业面试笔记1
- 操作系统常见面试题汇总
- 黑马程序员---反射
- 黑马程序员_JAVA的异常处理
- java面试中注意的问题01
- java 面试 奇葩点
- 写给程序员的一封信
- 面试常见算法-排序查找算法
- 黑马程序员-线程
- 黑马程序员---多线程
- PHP程序员经典面试回答,怎样回答面试官的问题
- 《人,绩效和职业道德》读后感
- 《人,绩效和职业道德》及博客读后感
- 《人,绩效和职业道德》读后感