解题思路
遍历两个链表,将值较小的结点用尾插法插入新链表中,最后将有剩余结点的链表直接插到新链表的尾部,返回新链表。
代码
class Solution {
public:ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {ListNode *head = new ListNode(0);ListNode *f = head;ListNode *p = l1;ListNode *q = l2;while(p && q){if(p->val < q->val){ListNode *tmp = p->next;p->next = NULL;f->next = p;f = f->next;p = tmp;}else{ListNode *tmp = q->next;q->next = NULL;f->next = q;f = f->next;q = tmp;}}f->next = p ? p : q;return head->next;}
};