Merge Two Sorted Lists
来源:互联网 发布:淘宝退款原因有影响吗 编辑:程序博客网 时间:2024/06/06 07:51
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. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { if(l1==null) return l2; if(l2==null) return l1; ListNode tmp=new ListNode(-1); for(ListNode node=tmp; l1!=null || l2!=null ;node=node.next){ int val1=(l1==null)?Integer.MAX_VALUE:l1.val; int val2=(l2==null)?Integer.MAX_VALUE:l2.val; if(val1<=val2){ node.next=l1; l1=l1.next; } else{ node.next=l2; l2=l2.next; } } return tmp.next; }}
通过递归解决:
/** * 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* res = NULL; if(l1->val <= l2->val){ res = l1; res->next = mergeTwoLists(l1->next, l2); } else { res = l2; res->next = mergeTwoLists(l1, l2->next); } return res; }};
0 0
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- Merge Two Sorted Lists
- ELF重定向对象文件 by wangdb
- 机房收费系统——只允许有一个MDI窗体的问题
- Linux中cat、more、less、head、tail内容查看命令解析与比较
- poj 1220 NUMBER BASE CONVERSION(字符串处理经典)
- 背包问题题型 龟兔赛跑 hdoj 2059
- Merge Two Sorted Lists
- 开篇
- 新浪天气接口XML处理方式,最终转成数组使用代码
- jQuery formValidator
- cocos2d-x使用tinyxml2解析&存储xml
- Android Activity的onCreate()函数
- 在mac终端中用颜色显示不同类型文件
- HTTP Status Code
- Python练习代码 -- 字符串和正则表达式, 文件文件夹操作