21 Merge Two Sorted Lists(合并两个排序

2018-09-21  本文已影响0人  有何不可12317

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) {
        ListNode *newNode = new ListNode(-1);
        ListNode *pNode = newNode;
        
        while (l1 && l2) {
            if (l1->val > l2->val) {
                pNode->next = l2;
                pNode = l2;
                l2 = l2->next;
            }
            else {
                pNode->next = l1;
                pNode = l1;
                l1 = l1->next;
            }
        }
        if (l1) pNode->next = l1;
        if (l2) pNode->next = l2;
        pNode = newNode->next;
        delete newNode;
        
        return pNode;
    }
};

参考链接:

  1. https://leetcode.com/problems/merge-two-sorted-lists/description/
上一篇 下一篇

猜你喜欢

热点阅读