码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Merge Two Sorted Lists

时间:2015-04-01 23:47:10      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:leetcode   c++   

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;
    }
};


[LeetCode] Merge Two Sorted Lists

标签:leetcode   c++   

原文地址:http://blog.csdn.net/kangrydotnet/article/details/44817825

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!