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

    本题就是简单的链表合成。时间:14ms

    我的代码:

    /**
    * 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 == NULL)
                return l2;
            if (l2 == NULL)
                return l1;
            ListNode *p1, *p2, *pHead, *pNext;
            p1 = l1, p2 = l2, pHead = pNext;
            while (p1!=NULL&&p2!=NULL){
                if (p1->val <= p2->val){
                    pNext->next = p1;
                    p1 = p1->next;
                }
                else{
                    pNext->next = p2;
                    p2 = p2->next;
                }
                pNext = pNext->next;
            }
            while (p1!=NULL){
                pNext->next = p1;
                p1 = p1->next;
                pNext = pNext->next;
            }
            while (p2!=NULL){
                pNext->next = p2;
                p2 = p2->next;
                pNext = pNext->next;
            }
            return pHead->next;
        }
    };
    “If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
  • 相关阅读:
    配置Log4j(非常具体)
    System.Net.WebClient.cs
    Code:获取指定汉字的首字母
    DBS:目录
    Jasper:推送 API
    Jasper-template
    Code:Base64 编码/解码
    DCloud-HTML5+:5+ App开发入门指南
    DCloud-HTML5+:barcode
    Nuget-QRCode:QRCoder
  • 原文地址:https://www.cnblogs.com/Scorpio989/p/4452573.html
Copyright © 2011-2022 走看看