21. Merge Two Sorted Lists 合并两个有

2019-07-08  本文已影响0人  xingzai

题目链接
tag:

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

相似题目:

上一篇 下一篇

猜你喜欢

热点阅读