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;
        }
    }
  • 相关阅读:
    Python开发【第六篇】循环语句
    Python开发【第四篇】语句与函数
    Python开发【第三篇】数据类型
    Python开发【第二篇】:初始Python
    2019-10-11入博客第一篇文章
    vim学习2-文档编辑
    vim学习1-入门指令
    linux学习9-进程管理知识
    linux学习8-正则表达式基础
    linux学习7-数据流重定向
  • 原文地址:https://www.cnblogs.com/skillking/p/9412047.html
Copyright © 2011-2022 走看看