zoukankan      html  css  js  c++  java
  • leetCode(8):merge two sorted list 分类: leetCode 2015-06-18 08:12 136人阅读 评论(0) 收藏

    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) {
            if(!l1)
        return l2;
        if(!l2)
        return l1;
        ListNode* head=NULL;
        head=((l1->val) < (l2->val))?  l1:l2;
        ListNode* p2=NULL;
        p2=((l1->val) >= (l2->val))?  l1:l2;
        
        ListNode* p1=head;
        
        while(p1->next && p2)
        {
        if((p1->next->val) <= (p2->val))
        p1=p1->next;
        else
        {
        ListNode* tmp1=p1->next;
        ListNode* tmp2=p2->next;
        p1->next=p2;
        p2->next=tmp1;
        p1=p2;
        p2=tmp2;
        }
        }
        
        if(!(p1->next))
        p1->next=p2;
        return head;
        }
    };


  • 相关阅读:
    枚举
    泛型
    装箱和拆箱
    使用TryParse()来执行数值转换
    参数数组
    checked和unchecked转换
    字符串不可变
    TCC : Tiny C Compiler (2018-2-6)
    win10 下 protobuf 与 qt
    QWebView 与Js 交互
  • 原文地址:https://www.cnblogs.com/zclzqbx/p/4687109.html
Copyright © 2011-2022 走看看