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

LeetCode_Merge Two Sorted Lists

时间:2015-07-01 23:40:09      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:c++   algorithm   leetcode   算法   

一.题目

Merge Two Sorted Lists

  Total Accepted: 63974 Total Submissions: 196044My Submissions

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.

Show Tags
Have you met this question in a real interview?  
Yes
 
No

Discuss






二.解题技巧

    这道题就是将两个已排序的列表的元素进行比较,当某一个列表的元素比较小的话,就将其加入到输出列表中,并将该列表的指针指向列表的下一个元素。这道题是比较简单的,但是有一个边界条件要注意,就是两个列表可能会出现为空的情况,如果l1为空时,可以直接将l2进行返回;如果l2为空时,可以直接将l1返回,这样可以减少很多计算量。


三.实现代码

#include <iostream>

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/


struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};


class Solution
{
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
    {
        if (!l1)
        {
            return l2;
        }

        if (!l2)
        {
            return l1;
        }

        ListNode Head(0);
        ListNode *Pre = &Head;

        while(l1 && l2)
        {
            if (l1->val < l2->val)
            {
                Pre->next = l1;
                l1 = l1->next;
                Pre = Pre->next;
            }
            else
            {
                Pre->next = l2;
                l2 = l2->next;
                Pre = Pre->next;
            }
        }

        while (l1)
        {
            Pre->next = l1;
            l1 = l1->next;
            Pre = Pre->next;
        }

        while(l2)
        {
            Pre->next = l2;
            l2 = l2->next;
            Pre = Pre->next;
        }

        return Head.next;

    }
};




四.体会

   这道题主要考察的就是边界条件,主要就是处理链表为空的情况,也就是,如果l1为空,就返回l2,如果l2为空,就直接返回l1。简单的题要考虑充分啊。



版权所有,欢迎转载,转载请注明出处,谢谢技术分享
技术分享




版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode_Merge Two Sorted Lists

标签:c++   algorithm   leetcode   算法   

原文地址:http://blog.csdn.net/sheng_ai/article/details/46716419

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