Leetcode 21 Merge Two Sorted Lists

原创 2016年08月30日 19:08:30

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.

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

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

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

http://blog.csdn.net/accepthjp/article/details/52356447

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


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

相关文章推荐

LeetCode笔记:21. Merge Two Sorted Lists

合并两个有序链表

Leetcode刷题记——21. Merge Two Sorted Lists(合并两有序链表)

一、题目叙述: Merge two sorted linked lists and return it as a new list. The new list should be...

LeetCode题解-21-Merge Two Sorted Lists

原题 本题较为简单,但是只想到了迭代的解法,没有想到递归。 迭代法 解题思路 比较L1与L2并增加新链表的节点,值为L1或者L2中较小的值。 代码 public c...

LeetCode 21 Merge Two Sorted Lists (C,C++,Java,Python)

Problem: Merge two sorted linked lists and return it as a new list. The new list should be made by ...

LeetCode算法题——21. Merge Two Sorted Lists

题目 Merge two sorted linked lists and return it as a new list. The new list should be made by splici...
  • LZTree
  • LZTree
  • 2017年04月12日 17:01
  • 149

21.[Leetcode]Merge Two Sorted Lists

题意:归并两个排好序的链表我的思路;我们没有考虑递归的方法,也没有想到用递归解决,先贴出c++的非递归/** * Definition for singly-linked list. * stru...

leetcode[21 链表]Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing t...

Leetcode21: Merge Two Sorted Lists

还是和链表有关的问题,和第二题比较像,代码如下 # Definition for singly-linked list. # class ListNode(object): # def _...

leetcode 21. Merge Two Sorted Lists

1.题目 Merge two sorted linked lists and return it as a new list. The new...

LeetCode_21---Merge Two Sorted Lists

LeetCode
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Leetcode 21 Merge Two Sorted Lists
举报原因:
原因补充:

(最多只允许输入30个字)