牛客题霸NC33题解

合并有序链表

牛客题霸NC33

难度:Easy

题目描述

将两个有序的链表合并为一个新链表,要求新的链表是通过拼接两个链表的节点来生成的。

输入

{1},{}

返回值

{1}

输入

{1},{1}

返回值

{1,1}

代码解决

算法入门基础题,尾插法扫描拼接即可:

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param l1 ListNode类 
     * @param l2 ListNode类 
     * @return ListNode类
     */
    public ListNode mergeTwoLists (ListNode l1, ListNode l2) {
        // write code here
        
        ListNode head = new ListNode(-1);
        ListNode tail = head;
        
        while(l1 != null || l2 != null){
            
            if(l1 != null && l2 != null){
                ListNode cur;
                if(l1.val < l2.val){
                    cur = l1;
                    l1 = l1.next;
                }
                else{
                    cur = l2;
                    l2 = l2.next;
                }
            
                tail.next = cur;
                tail = cur;
            }
            else{
                tail.next = l1 == null ? l2 : l1;
                break;
            }
            
            
        }
        
        
        return head.next;
        
        
    }
}
posted @ 2020-11-09 14:28  阿柒~  阅读(160)  评论(0编辑  收藏  举报