程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 算法:兩個有序鏈表的合並

算法:兩個有序鏈表的合並

編輯:C++入門知識

LeetCode OJ Problem: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.

class Solution {
public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        if(!l1)
            return l2;
        else if(!l2)
            return l1;
        ListNode *head, *r;
        if(l1->val < l2->val)
        {
             head = l1;
             l1 = l1->next;
        }
        else
        {
             head = l2;
             l2 = l2->next;
        }
        head->next = NULL;   
        r = head;
        while(l1 && l2)
        {
            if(l1->val < l2->val)
            {
                r->next = l1;
                r = l1;
                l1 = l1->next;
            }
            else
            {
                r->next = l2;
                r = l2;
                l2 = l2->next;
            }
            r->next = NULL;
        }
        if(!l1)
            r->next = l2;
        else if(!l2)
            r->next = l1;
        return head;
    }
};


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved