Leetcode 21. Merge Two Sorted Lists
2016-10-13 10:16
507 查看
原题链接:https://leetcode.com/problems/merge-two-sorted-lists/
![](https://img-blog.csdn.net/20161013101543869?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
思路:
0 处理边界条件
1 两个输入链表可能为空,采用dummy节点,使得dummy.next指向新链表的第一个节点。
2 初始化时,使用两个指针指向两个链表的表头,两个指针同时不为空时,取较小的节点放入新链表的尾部。
3 然后把链表中不为空的部分重新放到新链表的尾部。
什么情况下,我们需要使用dummy node?
http://blog.yangliu.online/2016/07/15/when-do-we-need-dummy-head-for-linked-list/
思路:
0 处理边界条件
1 两个输入链表可能为空,采用dummy节点,使得dummy.next指向新链表的第一个节点。
2 初始化时,使用两个指针指向两个链表的表头,两个指针同时不为空时,取较小的节点放入新链表的尾部。
3 然后把链表中不为空的部分重新放到新链表的尾部。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode mergeTwoLists(ListNode l1, ListNode l2) { //判断边界条件 if(l1==null && l2!=null) return l2; if(l1!=null && l2==null) return l1; if(l1==null && l2==null) return null; //创建头结点 ListNode head = new ListNode(0); ListNode current = head; while(l1!=null && l2!=null){ if(l1.val<=l2.val){//取较小值的节点 current.next = l1; current = current.next; l1 = l1.next; }else{ current.next = l2; current = current.next; l2 = l2.next; } } //将剩下的部分放置在合并后链表的尾部 if(l1!=null) current.next= l1; if(l2!=null) current.next=l2; return head.next; } }
什么情况下,我们需要使用dummy node?
http://blog.yangliu.online/2016/07/15/when-do-we-need-dummy-head-for-linked-list/
相关文章推荐
- [LeetCode]21. Merge Two Sorted Lists
- [leetcode 21] Merge Two Sorted Lists
- leetcode--21. Merge Two Sorted Lists
- (Java)LeetCode-21. Merge Two Sorted Lists
- leetcode 21. Merge Two Sorted Lists
- Leetcode 21 Merge Two Sorted Lists
- leetcode_21题——Merge Two Sorted Lists(链表)
- LeetCode 21 Merge Two Sorted Lists 把两个链表有序连接
- Leetcode 21:Merge Two Sorted Lists(golang实现合并两条已经排序的链表)
- LeetCode 【21. Merge Two Sorted Lists】
- leetcode21~Merge Two Sorted Lists
- 【leetcode】【单链表】【21】Merge Two Sorted Lists
- LeetCode - 21. Merge Two Sorted Lists
- 【Leetcode problrm 21】Merge Two Sorted Lists
- 编程题2- Merge Two Sorted Lists(leetcode-21)
- LeetCode - 21. Merge Two Sorted Lists
- leetcode: (21) Merge Two Sorted Lists
- LeetCode---(21)Merge Two Sorted Lists
- [Leetcode 21] 21 Merge Two Sorted Lists
- [LeetCode] 21 - Merge Two Sorted Lists