前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 21 Merge Two Sorted Lists

Leetcode 21 Merge Two Sorted Lists

作者头像
triplebee
发布2018-01-12 15:10:57
4500
发布2018-01-12 15:10:57
举报

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.

两个有序链表归并成一个有序链表,

其实比较优美的解法是用递归去解决,代码十分简洁,

然而我之前有题目这样做过了,就想用大众化的方法做一遍。

https://cloud.tencent.com/developer/article/1019320

代码语言:javascript
复制
/**
 * 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* p=new ListNode(0);
        ListNode* result=p;
        while(l1 && l2)
        {
            ListNode* t=new ListNode(0);
            p->next=t;
            p=p->next;
            if(l1->val<l2->val)
            {
                p->val=l1->val;
                l1=l1->next;
            }
            else
            {
                p->val=l2->val;
                l2=l2->next;
            }
            
        }
        p->next=l1?l1:l2;
        return result->next;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-08-30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档