合并两个排序的链表_JAVA_中等

合并两个排序的链表

http://www.nowcoder.com/questionTerminal/d8b6b4358f774294a89de2a6ac4d9337

  • 给一个初始节点赋给root,构建的链表连接在其后,返回时返回root.next
  • 两条链哪个小链接哪个节点,被链接的链后移,直到一条链为空,另一条链直接接在最后
public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        ListNode root = new ListNode(-1), node = root;

        // 直到一条链为空
        while(list1 != null && list2 != null){
            if(list1.val < list2.val) {
                node.next = list1;
                list1 = list1.next;
            } else {
                node.next = list2;
                list2 = list2.next;
            }
            node = node.next;
        }

        // 剩余连接
        node.next = list1 == null ? list2 : list1;
        return root.next;
    }
}
全部评论

相关推荐

08-30 15:51
已编辑
蚌埠坦克学院 Java
狸猫换offer:感觉hr写这段字的时候充满怨气
lastday知无不言
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务