美文网首页
21. Merge Two Sorted Lists 合并两个有

21. Merge Two Sorted Lists 合并两个有

作者: xingzai | 来源:发表于2019-07-08 17:13 被阅读0次

题目链接
tag:

  • Easy;

question
  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.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

思路:
  将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。本题比较简单,具体思路就是新建一个链表,依次比较两个链表中的元素值,把较小的那个链到新链表中。代码如下:

/**
 * 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) return l2;
        if (!l2) return l1;
        ListNode *dummy = new ListNode(-1);
        ListNode *cur = dummy;
        while (l1 || l2) {
            int val1 = l1 ? l1->val : INT_MAX;
            int val2 = l2 ? l2->val : INT_MAX;
            if (val1 <= val2) {
                cur->next = l1;
                l1 = l1->next;
            }
            else {
                cur->next = l2;
                l2 = l2->next;
            }
            cur = cur->next;
        }
        return dummy->next;
    }
};

相似题目:

相关文章

网友评论

      本文标题:21. Merge Two Sorted Lists 合并两个有

      本文链接:https://www.haomeiwen.com/subject/qzsahctx.html