刷题,练习手感!
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { if (l1 == NULL) return l2; if (l2 == NULL) return l1; ListNode* head, *cur, *tmp; head = getNext(l1, l2); cur = head; while (true) { if (l1 == NULL || l2 == NULL) break; cur->next = getNext(l1, l2); cur = cur->next; } if (l1 != NULL) cur->next = l1; if (l2 != NULL) cur->next = l2; return head; } ListNode* getNext(ListNode*& l1, ListNode*&l2) { if (l1->val > l2->val) { ListNode* t = l2; l2 = l2->next; return t; } else { ListNode* t = l1; l1 = l1->next; return t; } } };