/** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param l1 ListNode类 * @param l2 ListNode类 * @return ListNode类 */ ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { // write code here if (l1 == nullptr) return l2; if (l2 == nullptr) return l1; ListNode* l = nullptr; // 创建链表(头结点) ListNode** pNode = &l; // 给头结点一个指针 // l1和l2两个链表都没到空的过程不断给新链表通过比较赋值 while (l1 != nullptr && l2 != nullptr) { if (l1->val <= l2->val) { *pNode = new ListNode(l1->val); // 解引用的方式赋值 l1 = l1->next; } else { *pNode = new ListNode(l2->val); l2 = l2->next; } pNode = &((*pNode)->next); // 指针往链表的下一个元素移动 } // 谁为空,另一个就接着上 if (l1 == nullptr) { while (l2 != nullptr) { *pNode = new ListNode(l2->val); l2 = l2->next; pNode = &((*pNode)->next); } } else { while(l1 != nullptr) { *pNode = new ListNode(l1->val); l1 = l1->next; pNode = &((*pNode)->next); } } return l; // 返回新链表的头结点 } };