/** * 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) return l2; if (!l2) return l1; ListNode *p, *q, *r, *pHead; p = l1; q = l2; if (p->val <= q->val) { pHead = p; p = p->next; } else { pHead = q; q = q->next; } r = pHead; while (1) { if (!p) { r->next = q; break; } if (!q) { r->next = p; break; } if (p->val <= q->val) { r->next = p; r = p; p = p->next; } else { r->next = q; r = q; q = q->next; } } return pHead; } };
同样,也可以采用递归写法,见《剑指offer》