leetcode 21. Merge Two Sorted Lists

妖狐艹你老母 2022-06-09 08:00 316阅读 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.

Seen this question in a real interview before? Yes

简单的归并排序,不说了,直接上代码:

  1. /**
  2. * Definition for singly-linked list.
  3. * public class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) { val = x; }
  7. * }
  8. */
  9. public class Solution {
  10. public ListNode mergeTwoLists(ListNode l1, ListNode l2)
  11. {
  12. if(l1==null && l2==null)
  13. return l1;
  14. ListNode p=l1;
  15. ListNode q=l2;
  16. ListNode head=new ListNode(-1);
  17. ListNode next=head;
  18. // p q 值得是当前的位置上的结点
  19. while(p!=null && q!=null)
  20. {
  21. if(p.val < q.val)
  22. {
  23. next.next=new ListNode(p.val);
  24. next=next.next;
  25. p=p.next;
  26. }
  27. else if(p.val > q.val)
  28. {
  29. next.next=new ListNode(q.val);
  30. next=next.next;
  31. q=q.next;
  32. }else
  33. {
  34. next.next=new ListNode(p.val);
  35. next=next.next;
  36. next.next=new ListNode(q.val);
  37. next=next.next;;
  38. p=p.next;
  39. q=q.next;
  40. }
  41. }
  42. if(p!=null)
  43. next.next=p;
  44. if(q!=null)
  45. next.next=q;
  46. return head.next;
  47. }
  48. public static void main(String[] args)
  49. {
  50. Solution so=new Solution();
  51. so.mergeTwoLists(null, null);
  52. }
  53. }

下面是C++的做法,直接归并即可。

代码如下:

  1. #include <iostream>
  2. #include <stack>
  3. using namespace std;
  4. /*
  5. struct ListNode
  6. {
  7. int val;
  8. ListNode *next;
  9. ListNode(int x) : val(x), next(NULL) {}
  10. };
  11. */
  12. class Solution
  13. {
  14. public:
  15. ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
  16. {
  17. ListNode* head = new ListNode(-1);
  18. ListNode* a=head;
  19. while (l1 != NULL && l2 != NULL)
  20. {
  21. if (l1->val < l2->val)
  22. {
  23. a->next = new ListNode(l1->val);
  24. l1 = l1->next;
  25. a = a->next;
  26. }
  27. else
  28. {
  29. a->next = new ListNode(l2->val);
  30. l2 = l2->next;
  31. a = a->next;
  32. }
  33. }
  34. while (l1 != NULL)
  35. {
  36. a->next = new ListNode(l1->val);
  37. l1 = l1->next;
  38. a = a->next;
  39. }
  40. while (l2 != NULL)
  41. {
  42. a->next = new ListNode(l2->val);
  43. l2 = l2->next;
  44. a = a->next;
  45. }
  46. return head->next;
  47. }
  48. };

发表评论

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

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

相关阅读