• leetcode0021 mergetwosortedlists


    You are given the heads of two sorted linked lists list1 and list2.

    Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.

    Return the head of the merged linked list.

    Input: list1 = [1,2,4], list2 = [1,3,4]
    Output: [1,1,2,3,4,4]

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        /* apply the two-pointer technique */
        // public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        //     if(list1 == null) return list2;
        //     if(list2 == null) return list1;
        //     ListNode resultNode = new ListNode();
        //     ListNode p = resultNode;
        //     while(list1 != null && list2 != null){
        //         if(list1.val < list2.val){
        //             p.next = list1;
        //             list1 = list1.next;
        //         }else{
        //             p.next = list2;
        //             list2 = list2.next;
        //         }
        //         p = p.next;
        //     }
        //     if(list1 != null){
        //         p.next = list1;
        //     }
        //     if(list2 != null){
        //         p.next = list2;
        //     }
        //     return resultNode.next;
        // }
    
        /* apply the recursion technique */
        public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
            if(list1 == null) return list2;
            if(list2 == null) return list1;
            if(list1.val < list2.val){
                list1.next = mergeTwoLists(list1.next, list2);
                return list1;
            }
            list2.next = mergeTwoLists(list1, list2.next);
            return list2;
        }    
    }
    

    来源:力扣(LeetCode)
    链接:https://leetcode.cn/problems/merge-two-sorted-lists

  • 相关阅读:
    乐乐的作业
    Spring中配置数据源的5种形式
    乐观锁和悲观锁的区别
    使用Nexus搭建Maven私服
    Maven错误记录
    Maven学习笔记(一)
    Eclipse的SVN插件下载
    SSH整合(Struts2+Spring+Hibernate)
    java.lang.NoClassDefFoundError: org/objectweb/asm/Type
    使用mss2sql将SqlServer转换为Mysql
  • 原文地址:https://www.cnblogs.com/chenjo/p/16241048.html
Copyright © 2020-2023  润新知