Description
- 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.
Example
1 2
| Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4
|
Interface
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { } };
|
Solution
合并两个已按小到大排序的链表,最简单的做法就是新建一个链表,然后比较原有的两个链表当前节点的大小,然后选择较小的节点加到新建链表上,接着将被选中的链表的节点指向他的下一个,重复以上,知道某个链表已读到末尾或两个链表都为空,然后将未读完的链表的节点直接加到新建链表上就可以。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if (l1 == NULL) return l2; if (l2 == NULL) return l1; ListNode* head = new ListNode(0); ListNode* node = head; while (l1 != NULL && l2 != NULL) { if (l1->val < l2->val) { node->next = l1; l1 = l1->next; } else { node->next = l2; l2 = l2->next; } node = node->next; } node->next = (l1 == NULL ? l2 : l1); node = head; head = head->next; delete node; return head; } };
|
Improvement
还可以通过递归实现,原理与上面相同。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if (l1 == NULL) return l2; if (l2 == NULL) return l1; ListNode* node; if (l1->val < l2->val) { node = l1; node->next = mergeTwoLists(l1->next, l2); } else { node = l1; node->next = mergeTwoLists(l1, l2->next); } return node; } };
|
如有疑问请联系作者,联系方式:weijia_sysu@163.com