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;
        }
    }
  • 相关阅读:
    排名第一、第二的OCR软件
    补码输出
    枚举 与 枚举的应用
    动态构造结构体数组
    c 冒泡排序
    strcpy
    typedef用法
    C 结构体小结
    int 占一个机器字长
    SQL Server创建视图——视图的作用
  • 原文地址:https://www.cnblogs.com/skillking/p/9412047.html
Copyright © 2011-2022 走看看