class Solution { public: /** * @param l1: ListNode l1 is the head of the linked list * @param l2: ListNode l2 is the head of the linked list * @return: ListNode head of linked list */ ListNode * mergeTwoLists(ListNode * l1, ListNode * l2) { // write your code here if (!l1) return l2; if (!l2) return l1; ListNode *head; if (l1->val <= l2->val) { head = new ListNode(l1->val); l1 = l1->next; } else { head = new ListNode(l2->val); l2 = l2->next; } ListNode *cur = head; while (l1 && l2) { if (l1->val <= l2->val) { ListNode *temp = new ListNode(l1->val); cur->next = temp; cur = cur->next; l1 = l1->next; } else { ListNode *temp = new ListNode(l2->val); cur->next = temp; cur = cur->next; l2 = l2->next; } } if (!l1) cur->next = l2; else cur->next = l1; return head; } };
-------------end of file
thanks for reading-------------