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

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/
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容