首页 > 其他 > 详细

[LeetCode] Merge Two Sorted Lists

时间:2015-04-01 23:45:05      阅读:281      评论:0      收藏: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->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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!