leetcode做题总结,题目Merge Two Sorted Lists 2012/03/30
来源:互联网 发布:免费喊单软件 编辑:程序博客网 时间:2024/06/06 09:08
两有序链表归并,归并排序即可。
public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode l3 = new ListNode(0); ListNode st = l3; while(l1!=null&&l2!=null){ if(l1.val>l2.val){ l3.next = new ListNode(l2.val); l2=l2.next; l3=l3.next; }else{ l3.next = new ListNode(l1.val); l1=l1.next; l3=l3.next; } } while(l1!=null){ l3.next = new ListNode(l1.val); l1=l1.next; l3=l3.next; } while(l2!=null){ l3.next = new ListNode(l2.val); l2=l2.next; l3=l3.next; } return st.next; }
Update 2015/08/20: 上面的答案有两个缺陷,第一是没有必要定义一个0节点,可以直接使用引用,二是在其中一个链为空之后没有必要再使用while,可以直接使用if连接即可
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param ListNode l1 is the head of the linked list * @param ListNode l2 is the head of the linked list * @return: ListNode head of linked list */ public ListNode mergeTwoLists(ListNode l1, ListNode l2) { // write your code here if (l1 == null) return l2; if (l2 == null) return l1; ListNode head; if (l1.val <= l2.val){ head = l1; l1 = l1.next; } else { head = l2; l2 = l2.next; } ListNode start = head; while (l1 != null && l2 != null){ if (l1.val <= l2.val){ head.next = l1; l1 = l1.next; } else { head.next = l2; l2 = l2.next; } head = head.next; } if (l1 != null){ head.next = l1; } if (l2 != null){ head.next = l2; } return start; }}
0 0
- leetcode做题总结,题目Merge Two Sorted Lists 2012/03/30
- leetcode做题总结,题目Merge k Sorted Lists 2012/02/13
- leetcode 30: Merge Two Sorted Lists
- LeetCode: Merge Two Sorted Lists
- [Leetcode] Merge Two Sorted Lists
- Leetcode: Merge Two Sorted Lists
- [LeetCode] Merge Two Sorted Lists
- [Leetcode] Merge two sorted lists
- leetcode Merge Two Sorted Lists
- [LeetCode]Merge Two Sorted Lists
- [leetcode]Merge Two Sorted Lists
- LeetCode-Merge Two Sorted Lists
- [leetcode] Merge Two Sorted Lists
- [LeetCode] Merge Two Sorted Lists
- LeetCode - Merge Two Sorted Lists
- LeetCode:Merge Two Sorted Lists
- LeetCode | Merge Two Sorted Lists
- 【leetcode】Merge Two Sorted Lists
- Android开发之Junit测试
- hdu 1009 FatMouse' Trade
- jQuery_review之textarea的放大和缩小的jQuery实现
- R语言之机器学习
- {{引擎算法机制
- leetcode做题总结,题目Merge Two Sorted Lists 2012/03/30
- 订书机凤凰飞机头护卫舰可怜认购金额离开可怜风格迥然
- Win7安装Web.py,UnicodeDecodeError: 'ascii' codec can't decode byte 0xb0 in position 1: ordinal not in
- 杭电2019 int a[100100];数组大的定义在main()外面,记得后面加上“;”
- static_cast, dynamic_cast, reinterpret_cast, const_cast区别比较
- Swift源码分析----swift-account-replicator(1)
- UITableView的最后一行在3.5寸屏上无法显示的问题
- memcpy memmove区别和实现
- opencv小知识: