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

    Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
    
    Example:
    
    Input: 1->2->4, 1->3->4
    Output: 1->1->2->3->4->4
    

    解答:
    定义节点:

    class ListNode {
        int val;
        ListNode next;
    
        ListNode(int x) {
            val = x;
        }
    }
    

    思路:比较两个链表的头结点大小,小的节点加入新链表里面,最后剩余的一个链表全部加入新链表里面。
    Attention:leetcode上面的链表头结点是存储值的。

    class Solution {
        public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
            //合并链表,比较大小  首先你确实需要一个头结点来存储
            // 还有实时指向尾结点的指针
            ListNode head = new ListNode(0);
            ListNode temp = head;
            while (l1 != null && l2 != null) {
                if (l1.val <= l2.val) {
                    temp.next = l1;
                    l1 = l1.next;
                } else {
                    temp.next = l2;
                    l2 = l2.next;
                }
                temp = temp.next;
            }
            if (l1 != null) {
                temp.next = l1;
            }
            if (l2 != null) {
                temp.next = l2;
            }
            return head.next;
        }
    }
    
  • 相关阅读:
    Zero Downtime Upgrade of Oracle 10g to Oracle 11g Using GoldenGate — 1
    架构-MVVM:MVVM核心概念
    架构-MVVC:百科
    架构:目录
    架构:template
    JavaScript-Tool:Ext JS
    JavaScript-Tool:jquery.tree.js-un
    JavaScript-Tool:wdtree
    C#:C# 运算符
    C#:目录
  • 原文地址:https://www.cnblogs.com/d9e84208/p/12006919.html
Copyright © 2011-2022 走看看