当前位置:   article > 正文

LeetCode 21.合并两个有序链表_listnode(): val(0), next(nullptr){} listnode(int x

listnode(): val(0), next(nullptr){} listnode(int x): val(x) next(nullptr

每次比较两个首节点,取小,循环比较拿取即可

  1. /*
  2. * 思路:两个链表首节点比较,取小者,循环比较插入即可
  3. */
  4. struct ListNode {
  5. int val;
  6. ListNode* next;
  7. ListNode() : val(0), next(nullptr) {}
  8. ListNode(int x) : val(x), next(nullptr) {}
  9. ListNode(int x, ListNode* next) : val(x), next(next) {}
  10. };
  11. class Solution {
  12. public:
  13. ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
  14. ListNode* head = nullptr, * tail = nullptr;
  15. head = tail = new ListNode();
  16. while (list1 && list2)
  17. {
  18. if (list1->val < list2->val)
  19. {
  20. tail->next = list1;
  21. list1 = list1->next;
  22. }
  23. else{
  24. tail->next = list2;
  25. list2 = list2->next;
  26. }
  27. tail = tail->next;
  28. }
  29. if (!list1)
  30. tail->next = list2;
  31. if (!list2)
  32. tail->next = list1;
  33. return head->next;
  34. }
  35. };

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/904122
推荐阅读
相关标签
  

闽ICP备14008679号