21. Merge Two Sorted Lists


做题历程:

  1. 应该做了不止两次了,独立解出,用时4分钟

本题纯粹是考Linked List的基本功,没啥好说的,唯一需要注意的就是本题为了简化,需要加一个virtual node,但这应该也算很常规的处理了,直接上代码了。 代码如下:

/**
 * 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* virtual_node = new ListNode(-1);
        ListNode* head = virtual_node;
        while (l1 != nullptr && l2 != nullptr) {
            if (l1->val < l2->val) {
                head->next = l1;
                l1 = l1->next;
            }
            else {
                head->next = l2;
                l2 = l2->next;
            }
            head = head->next;
        }
        if (l1 != nullptr) {
            head->next = l1;
        }
        if (l2 != nullptr) {
            head->next = l2;
        }
        return virtual_node->next;
    }
};

results matching ""

    No results matching ""