C++/代码:
class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { auto dummy = new ListNode(-1); //定义一个虚拟表头 auto cur = dummy; //定义一个移动节点 while (pHead1 && pHead2) { //遍历 if (pHead1->val < pHead2->val) { //小的数放前面 cur->next = pHead1; //1->3 pHead1 = pHead1->next; } else { cur->next = pHead2; //1->3 pHead2 = pHead2->next; } cur = cur->next; } if (pHead1) cur->next = pHead1; //因为最后总会多一个数,无法进行比较的 else cur->next = pHead2; //所以那个链表多了就放那个链表中的数到最后 return dummy->next; } };