题解 | #合并有序链表#
合并有序链表
http://www.nowcoder.com/practice/a479a3f0c4554867b35356e0d57cf03d
class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(l1 == nullptr) return l2; if(l2 == nullptr) return l1; ListNode* newHead = nullptr, *newEnd = nullptr; ListNode* getNode = nullptr; while(l1 && l2){ getNode = l1->val < l2->val?l1:l2; getNode == l1?l1 = l1->next:l2 = l2->next; !newHead?newHead = newEnd = getNode:newEnd=newEnd->next = getNode; } while(l1){ newEnd = newEnd->next = l1; l1 = l1->next; } while(l2){ newEnd = newEnd->next = l2; l2 = l2->next; } return newHead; } };