LeetCode 21.Merge Two Sorted Lists

来源:互联网 发布:java接口特点是什么 编辑:程序博客网 时间:2024/06/06 20:38

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

链表数据域顺序是由小到大的,因此当l1**当前节点的值大于l2当前节点**的值时,我们取的是l2这个较小的值,并将l2的下一个节点的值和l1当前节点的值放到下一次做对比,依次递归下去。
一般解法:

ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {        ListNode *head = new ListNode(0), *p = head;        while (l1&&l2)        {            if (l1->val > l2->val)            {                p->next = l2;                l2 = l2->next;            }            else            {                p->next = l1;                l1 = l1->next;            }            p = p->next;        }        p->next = (l1 == NULL) ? l2 : l1;        return head->next;    }

这种写法其实不太好,会破环原链表的结构。

然后在discuss里看到一种优雅的递归写法:
https://leetcode.com/problems/merge-two-sorted-lists/discuss/

ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {        if (!l1) return l2;        if (!l2) return l1;        if (l1->val < l2->val) {            l1->next = mergeTwoLists(l1->next, l2);            return l1;        }        else {            l2->next = mergeTwoLists(l1, l2->next);            return l2;        }    }
原创粉丝点击