Merge Two Sorted Lists

本是古典 何须时尚 2022-01-05 10:39 251阅读 0赞

题目描述:

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.

  直接贴答案了。

solution:

  1. struct ListNode {
  2. int val;
  3. ListNode *next;
  4. ListNode(int x) : val(x), next(NULL) {}
  5. };
  6. ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
  7. if(l1 == NULL)
  8. return l2;
  9. if(l2 == NULL)
  10. return l1;
  11. ListNode *head = new ListNode(0);
  12. ListNode *p = head;
  13. while (l1 != NULL && l2 != NULL)
  14. {
  15. if (l1->val < l2->val)
  16. {
  17. p->next = l1;
  18. l1 = l1->next;
  19. }
  20. else
  21. {
  22. p->next = l2;
  23. l2 = l2->next;
  24. }
  25. p = p->next;
  26. }
  27. p->next = l1 ? l1 : l2;
  28. return head->next;
  29. }

递归解法:

  1. ListNode* mergeTwoLists(ListNode *l1, ListNode *l2)
  2. {
  3. if(l1 == NULL)
  4. return l2;
  5. if(l2 == NULL)
  6. return l1;
  7. if (l1->val < l2->val)
  8. {
  9. l1->next = mergeTwoLists(l1->next, l2);
  10. return l1;
  11. }
  12. else
  13. {
  14. l2->next = mergeTwoLists(l2->next, l1);
  15. return l2;
  16. }
  17. }

转载于:https://www.cnblogs.com/gattaca/p/4359877.html

发表评论

表情:
评论列表 (有 0 条评论,251人围观)

还没有评论,来说两句吧...

相关阅读