Merge Two Sorted Lists

原创 2015年11月19日 12:50:37

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.

用了一个dumb head,。对于这种header不确定的list,可以用dumb header,代码会整洁不少。

/**
 * 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) {
        ListNode dumHeader = new ListNode(0);
        ListNode current = dumHeader;
        while(l1 != null && l2 != null){
            ListNode nextNode = null;
            if(l1.val > l2.val){
                nextNode = l2;
                l2 = l2.next;
                current.next = nextNode;
                current = nextNode;
            }
            else if(l2.val >= l1.val){
                nextNode = l1;
                l1 = l1.next;
                current.next = nextNode;
                current = nextNode;
            }
        }
        
        if(l1 != null){
            current.next = l1;
        }
        else if (l2 != null){
            current.next = l2;
        }
        
        return dumHeader.next;
    }
}


面试题17:合并两个有序链表(Leetcode-21:Merge Two Sorted Lists)

思路与合并两个有序数组是一样的, 重新建立一个node l3,同时遍历l1和l2,比较小的数就插入到l3的表尾,然后小的数指针后移。 不同的是,在遍历之前,得要先建立l3的头结点,也就是比较l1和l2...

Merge Two Sorted Lists(和并两个从小到大排好序的链表)

描述: Merge two sorted linked lists and return it as a new list. The new list should be made by spli...

[LeetCode] 021. Merge Two Sorted Lists (Easy) (C++/Python)

[LeetCode] 021. Merge Two Sorted Lists (Easy) (C++/Python)
  • hcbbt
  • hcbbt
  • 2015年03月04日 20:11
  • 3441

leetcode Merge Two Sorted Lists

题目:https://oj.leetcode.com/problems/merge-two-sorted-lists/ 题意:按从小到大,把两个已经排好序的链表合并 没啥思路,直接往下接就行了,我...

[leetcode-排序]--21. Merge Two Sorted Lists

Question 21. Merge Two Sorted Lists Merge two sorted linked lists and return it as a new list. The...

【LeetCode】Merge Two Sorted Lists

题目 Merge two sorted linked lists and return it as a new list. The new list should be made by splici...

LeetCode: Merge Two Sorted Lists

随手点进去forum, 看了两个答案,差不多的,都是一边merge value一边new ListNode。。。 难道不看题么? Merge two sorted linked lists and ...

LeetCode:Merge Two Sorted Lists

Merge Two Sorted Lists1、题目: Merge two sorted linked lists and return it as a new list. The new list...
  • BestZem
  • BestZem
  • 2016年07月11日 17:16
  • 131

LeetCode|Merge Two Sorted Lists

【问题描述】 Merge two sorted linked lists and return it as a new list. The new list should be made by sp...

LeetCode 之 Merge Two / k Sorted Lists — C/C++ 实现

Merge Two Sorted Lists   Merge two sorted linked lists and return it as a new list. The new list sh...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Merge Two Sorted Lists
举报原因:
原因补充:

(最多只允许输入30个字)