LeetCode: Merge Two Sorted Lists

原创 2016年08月31日 00:08:03

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.


源代码:

/**
 * 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) {
    if (l1 == NULL) return l2;
    if (l2 == NULL) return l1;
    
    struct ListNode* head = new ListNode(0);
    struct ListNode* tmp = head;
    while(l1 != NULL && l2 != NULL){

        if (l1->val > l2->val) {
            tmp->next = l2;
            l2 = l2->next;
        }
        else {
            tmp->next = l1;
            l1 = l1->next;
        }
        tmp = tmp->next;        
    }
    if (l1 != NULL) tmp->next = l1;
    if (l2 != NULL) tmp->next = l2;
    
    return head->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
  • 123

[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
  • 235
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:LeetCode: Merge Two Sorted Lists
举报原因:
原因补充:

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