zoukankan      html  css  js  c++  java
  • LeetCode-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.

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            ListNode* root;
            ListNode* tail;
            if(l1!=NULL&&l2!=NULL){
                if(l1->val>l2->val){
                    root=l2;
                    tail=root;
                    l2=l2->next;
                }
                else{
                    root=l1;
                    tail=root;
                    l1=l1->next;
                }
                while(l1!=NULL&&l2!=NULL){
                    if(l1->val>l2->val){
                        tail->next=l2;
                        tail=tail->next;
                        l2=l2->next;
                    }
                    else{
                        tail->next=l1;
                        tail=tail->next;
                        l1=l1->next;
                    }
                }
                if(l1!=NULL)tail->next=l1;
                if(l2!=NULL)tail->next=l2;
                return root;
            }
            else{
                if(l2==NULL)return l1;
                else return l2;
            }
        }
    };
    
  • 相关阅读:
    text/css什麼意思
    w3cschool的在線編輯器的特點
    html
    notepad编写html
    html学习心得
    html 链接
    資料鏈接
    微信小程序的界面下拉刷新
    C# PictureBox控件畫圖
    CPK公式
  • 原文地址:https://www.cnblogs.com/superzrx/p/3322528.html
Copyright © 2011-2022 走看看