21. Merge Two Sorted Lists
来源:互联网 发布:linux系统中文版 编辑:程序博客网 时间:2024/06/01 15:48
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.
// recursive solution, time O(m+n), much more space complexity
/** * 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; } }};
my 非递归法
class Solution {public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(l1 == NULL) return l2; if(l2 == NULL) return l1; ListNode* p = l1; ListNode* q = l2; ListNode* x = (l1->val <= l2->val) ? l1 :l2; ListNode* c; while(p&&q) { if(p->val <=q->val) { c->next = p; c = c->next; p = p->next; } else { c->next = q; c = c->next; q = q->next; } } if(!p) { c->next = q; } if(!q) { c->next = p; } return x; }};
// merge sort, adding while comparing, time O(m+n)class Solution_MergeSort {public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode dummy(0); //头! ListNode *curr = &dummy; while (l1 && l2) { if (l1->val < l2->val) { curr->next = l1; curr = l1; l1 = l1->next; } else { curr->next = l2; curr = l2; l2 = l2->next; } } if (!l1) { curr->next = l2; } if (!l2) { curr->next = l1; } return dummy.next; }};
0 0
- 21.Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21.Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- 21. Merge Two Sorted Lists
- PHP与理在事先
- MyBatis之传入参数
- 自定义Dialog
- mysql技术内幕总结篇 (一)存储程序和视图的安全性
- mysql 2个服务器之间访问数据
- 21. Merge Two Sorted Lists
- Android 透明状态栏和导航栏
- 调用WebService的几种方式
- Android笔记——Button点击事件几种写法
- web项目关于 jquery easyui 与后台数据交互
- 关于访问相对路径问题
- linux批量ping域名的脚本
- Linux杂谈:解决配置静态ip后eth0网卡启动不了的问题
- 怎么查看ubuntu是多少位和常用信息