[LeetCode] Merge Two Sorted Lists

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.

解题思路:

这道题是我做的leetcode最容易的题目了。其中有个小技巧,就是在最开始的时候申请一个头结点,然后在融合之后再删除头结点。这样能够让代码更加清晰。利用原有的空间,更加加快了效率,在leetcode跑的时间仅仅13ms。Talk is cheap, show you the cade:

/**
 * 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=new ListNode(0);
        ListNode* p = head;       //指向融合的最后一个元素
        while(l1!=NULL&&l2!=NULL){
            if(l1->val<l2->val){
                p->next=l1;
                p=l1;
                l1=l1->next;
            }else{
                p->next=l2;
                p=l2;
                l2=l2->next;
            }
        }
        while(l1!=NULL){
            p->next=l1;
            p=l1;
            l1=l1->next;
        }
        while(l2!=NULL){
            p->next=l2;
            p=l2;
            l2=l2->next;
        }
        p->next = NULL;
        p=head;
        head=head->next;
        delete p;
        return head;
    }
};


0 条评论

    发表评论

    电子邮件地址不会被公开。 必填项已用 * 标注