ITPub博客

首页 > > > [LeetCode] Merge Two Sorted Lists

[LeetCode] Merge Two Sorted Lists

作者:Ruiyuan Li 时间:2015-04-01 00:00:00 0 删除 编辑

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->valval){
                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;
    }
};


转载请注明: » [LeetCode] Merge Two Sorted Lists
<!-- -->

原文作者:;如有侵权,请联系管理员删除。

上一篇: 穿越时空的思念
请登录后发表评论 登录
全部评论

注册时间:2020-05-21

  • 博文量
    495
  • 访问量
    4824