letecode [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.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

题目大意:

  给定两个链表,按照从小到大的顺序排列成一个链表。以原先链表作为基础。

理  解:

  若l1->val 小于等于l2->val,则选择l1的结点组成新链表。否则选择l2的结点组成新链表。

  ( 也可递归实现 )

代  码 C++:

/**
 * 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) {
        ListNode* head;
        if(l1==NULL) return l2;
        if(l2==NULL) return l1;
        if(l1->val<=l2->val){
            head = l1;
            l1 = l1->next;
        }else{
            head = l2;
            l2 = l2->next;
        }
        ListNode* p = head;
        while(l1!=NULL && l2!=NULL){
            if(l1->val<=l2->val){
                p->next = l1;
                p = p->next;
                l1 = l1->next;
            }else{
                p->next = l2;
                p = p->next;
                l2 = l2->next;
            }
        }
        if(l1==NULL){
            p->next = l2;
        }
        if(l2==NULL){
            p->next = l1;
        }
        return head;
    }
};

运行结果:

  执行用时 : 16 ms  内存消耗 : 8.8 MB
posted @ 2019-05-30 15:39  lpomeloz  阅读(101)  评论(0)    收藏  举报