【EASY】Merge Two Sorted Lists

发布于: 2018-12-20 22:16
阅读: 83
评论: 0
喜欢: 0

问题

原题链接:https://leetcode.com/problems/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

分析过程

  • 输入:两个有序的链表
  • 输出:合成一整个链表
  • 思路:新建一个根节点,然后按次序扫描两个链表,重新挂接链表。

解决方法

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if (!l1 || !l2) {
            return l1 ?: l2;
        }
        
        ListNode *tmpA = l1, *tmpB = l2;
        // 新建一个根节点用于往后挂接
        ListNode newList = ListNode(0);
        // 正在挂接的节点
        ListNode *tmp = &newList;
        
        while (tmpA && tmpB) {
            if (tmpA->val <= tmpB->val) {
                tmp->next = tmpA;
                tmpA = tmpA->next;
            } else {
                tmp->next = tmpB;
                tmpB = tmpB->next;
            }
            tmp = tmp->next;
        }
        // 其中一个链表空了,此时把另一个挂上去
        tmp->next = tmpA ?: tmpB;
        
        return newList.next;
    }
};

Thanks for reading.

All the best wishes for you! 💕