21.合并两个有序链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        ListNode* l1 = list1;
        ListNode* l2 = list2;
        ListNode* head = new ListNode(0), *curr = head;
        
        while (l1 && l2) { //是&&,不是||!
            if (l1->val < l2->val) {
                head->next = l1;
                l1 = l1->next;
            }
            else {
                head->next = l2;
                l2 = l2->next;
            }
            head = head->next;
        }
        head->next = (l1 == nullptr) ? l2 : l1;//结束后若还有余出来的链表,将head直接接在上面
        return curr->next;
    }
};

这个代码的格式有点像归并排序(双指针)

你可能感兴趣的:(#,链表,Leetcode,链表,排序算法,数据结构)