题解 | #合并有序链表#

合并有序链表

http://www.nowcoder.com/practice/a479a3f0c4554867b35356e0d57cf03d

思路:

  • 两个链表当前节点非空,每次比较当前两个节点
  • 设置辅助头节点,返回方便处理
  • 直接将一个非空的添加到结果
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) {
        //处理特殊情况
        if(l1 == null) return l2;
        if(l2 == null) return l1;

        //设置辅助头节点
        ListNode head = new ListNode(0);
        ListNode cur = head;

        //循环处理每两个当前非空节点
        while(l1 != null && l2 != null){
            if(l1.val <= l2.val){
                cur.next = l1;
                l1 = l1.next;
            } else {
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }

        //将非空的链表直接添加到结果
        cur.next = (l1 == null)? l2 : l1;

        //返回辅助头节点的next
        return head.next;
    }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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