021 Merge Two Sorted Lists [Leetcode]
2015-10-27 16:53
357 查看
题目内容:
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.
解题思路:
很基础的问题,注意处理长度不等的问题,同样使用附加头结点化简处理。
非递归实现代码如下,运行时间8ms:
递归实现:
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.
解题思路:
很基础的问题,注意处理长度不等的问题,同样使用附加头结点化简处理。
非递归实现代码如下,运行时间8ms:
/** * 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; ListNode *p1(l1), *p2(l2), *pre_head(new ListNode(0)), *cur(pre_head); while (p1 != NULL && p2 != NULL) { if (p1->val < p2->val) { cur->next = p1; p1 = p1->next; } else { cur->next = p2; p2 = p2->next; } cur = cur->next; } if (p1 != NULL) { cur->next = p1; } else if (p2 != NULL) { cur->next = p2; } ListNode *head = pre_head->next; pre_head->next = NULL; delete pre_head; return head; } };
递归实现:
/** * 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(l1, l2->next); return l2; } } };
相关文章推荐
- Shot(三分)
- Ehcache(03)——Ehcache中储存缓存的方式
- 工厂方法及其设计原则
- iOS开发UI篇—Quartz2D简单使用(三)
- Flume学习07 — FlumeRpcClientUtils工具类
- 修改圆角个数
- Selinux
- 对象持久化
- 2015生命之旅---第一站重庆
- volatile的作用
- eclipse下使用MultiDex解决65536限制
- 3.4
- shell三件利器——管道,重定向和backtick
- tcp三次握手、socket编程
- zabbix-agent客户端安装
- 简要总结破解myeclipse10的方法
- JDBC操作数据库
- Android判断输入框的状况
- LU分解
- 016.getter= setter= 属性特性