zoukankan      html  css  js  c++  java
  • 21. Merge Two Sorted Lists

    一、题目

      1、审题

        

      2、分析

        合并两个有序的链表元素组成一个新链表。

    二、解答

      1、分析:

        方法一:

          依次比较两个链表中的元素,依次取数值小的元素插入新的链表。

      

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    
            ListNode head = new ListNode(0);
            ListNode tempNode = head;
            
            while(l1 != null && l2 != null) {
                if(l1.val < l2.val) {
                    tempNode.next = new ListNode(l1.val);
                    l1 = l1.next;
                }
                else {
                    tempNode.next = new ListNode(l2.val);
                    l2 = l2.next;
                }
                tempNode = tempNode.next;
            }
            
            while(l1 != null) {
                tempNode.next = new ListNode(l1.val);
                tempNode = tempNode.next;
                l1 = l1.next;
            }
            while(l2 != null) {
                tempNode.next = new ListNode(l2.val);
                tempNode = tempNode.next;
                l2 = l2.next;
            }
            return head.next;
        }
    }

        方法二:

          直接在两个链表之间进行比较,将值得大小插入第一个链表,最终返回第一个链表。

      

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    
            ListNode head = new ListNode(0);
            ListNode cur = head;
            head.next = l1;
    
            while(l1 != null && l2 != null) {
                if(l1.val < l2.val) {
                    l1 = l1.next;
                }
                else {      // l2 头结点插入  l1
                    ListNode next = l2.next;
                    l2.next = l1;
                    cur.next = l2;
                    l2 = next;
                }
                cur = cur.next;
            }
    
            if(l2 != null)
                cur.next = l2;
            return head.next;
        }
    }
  • 相关阅读:
    DP问题之最长非降子序列
    CentOS 6.8 编译安装MySQL5.5.32
    [Linux] killall 、kill 、pkill 命令详解
    编写登陆接口
    python学习day01
    python购物车程序
    ERROR:Attempting to call cordova.exec() before 'deviceready'
    BSF脚本引擎‘改变’Bean
    Solr安装配置
    amchart配置备忘
  • 原文地址:https://www.cnblogs.com/skillking/p/9412047.html
Copyright © 2011-2022 走看看