21. Merge Two Sorted Lists
2016-04-27 12:05
281 查看
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
一:递归写法
,感觉比较难理解==
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
};
二:非递归写法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
一:递归写法
,感觉比较难理解==
class Solution {
public:
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
if(l1->val < l2->val) { l1->next = mergeTwoLists(l1->next, l2); return l1; } else { l2->next = mergeTwoLists(l2->next, l1); return l2; } }
};
二:非递归写法
ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { if(NULL == l1) return l2; if(NULL == l2) return l1; ListNode* head=NULL; // head of the list to return // find first element (can use dummy node to put this part inside of the loop) if(l1->val < l2->val) { head = l1; l1 = l1->next; } else { head = l2; l2 = l2->next; } ListNode* p = head; // pointer to form new list // I use && to remove extra IF from the loop while(l1 && l2){ if(l1->val < l2->val) { p->next = l1; l1 = l1->next; } else { p->next = l2; l2 = l2->next; } p=p->next; } // add the rest of the tail, done! if(l1) p->next=l1; else p->next=l2; return head; }
相关文章推荐
- SQLITE中文编码转换问题
- jsp代理实现ajax跨域调用获取数据
- Java身份证验证方法
- C++作业4
- C# MVC模式下商品抽奖
- java synchronized详解
- HttpClient 教程 (A)
- js修改dom结构或样式时出错ie8下
- 如何在服务端插件中实现交互式的提示
- 详解Java设计模式编程中的Flyweight享元模式的开发结构
- 【数据结构】将一组数据升序排序(利用堆排序)
- Linux内存文件系统
- Android Spinner
- 基于Sphinx的实例解析:DISCUZ全文检索
- 【MVC-自定义过滤器】
- CentOS 6 使用 yum 安装MongoDB及服务器端配置
- Activity的生命周期和启动模式
- 安装vmware tools 灰色 的解决方案
- 今天改bug遇到一个ie8样式错乱问题
- Visual Studio Code进行Python开发