Leetcode: Merge Two Sorted Lists

原创 2016年08月31日 16:44:19
/**
 * 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 *ans=new ListNode(0);
        ListNode *answer=ans;
        while(l1 && l2){
            if(l1->val<l2->val){
                ans->next=l1;
                ans=ans->next;
                l1=l1->next;
            }
            else{
                ans->next=l2;
                l2=l2->next;
                ans=ans->next;
            }
        }
        if(l1){
            ans->next=l1;
        }
        if(l2){
            ans->next=l2;
        }
        
        return answer->next;
    }
};

版权声明:本文为博主原创文章,欢迎指教~

相关文章推荐

LeetCode笔记:21. Merge Two Sorted Lists

合并两个有序链表

LeetCode021 Merge Two Sorted Lists

详细见:leetcode.com/problems/merge-two-sorted-lists Java Solution: github package leetcode; im...
  • zxwtry
  • zxwtry
  • 2017年03月30日 11:21
  • 103

[LeetCode] Merge Two Sorted Lists 解题报告

[题目] Merge two sorted linked lists and return it as a new list. The new list should be made by spli...

LeetCode OJ——Merge Two Sorted Lists

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

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

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

《leetCode》:Merge Two Sorted Lists

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

Merge Two Sorted Lists - Leetcode

题意:合并两个有序链表。 思路:此题难易程度是easy,在数据结构书中讲链表这一块有这个题目出现。做法很简单,分别用指针指向两个链表,比较指针所指的值大小,将值小的那一项放入新链表中,并将该指针向后...

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 OJ算法题(六十四):Merge Two Sorted Lists

题目: Merge two sorted linked lists and return it as a new list. The new list should be made by splic...
  • op_yu
  • op_yu
  • 2014年08月26日 21:51
  • 223
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Leetcode: Merge Two Sorted Lists
举报原因:
原因补充:

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