Leetcode: Merge Two Sorted Lists

秒速五厘米 2022-08-07 05:40 121阅读 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.

这道题和前面Leetcode: Merge Sorted Array 这道题看似类似,因为数据结构的不同,但是解法还是有一些不同的。

C++代码示例:

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution
  10. {
  11. public:
  12. ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)
  13. {
  14. //helper指向l1和l2指向最小的哪一个,一直循环着找下去
  15. ListNode *helper = new ListNode(0);
  16. ListNode *head = helper;
  17. while (l1 && l2)
  18. {
  19. if (l1->val < l2->val)
  20. {
  21. helper->next = l1;
  22. l1 = l1->next;
  23. }
  24. else
  25. {
  26. helper->next = l2;
  27. l2 = l2->next;
  28. }
  29. helper = helper->next;
  30. }
  31. //如果最后l1或者l2还有指向的数据,直接接到helper的后面
  32. if (l1) helper->next = l1;
  33. if (l2) helper->next = l2;
  34. return head->next;
  35. }
  36. };

发表评论

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

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

相关阅读