当前位置:   article > 正文

LeetCode@LinkedList_21_Merge_Two_Sorted_Lists_java linkedlist merge(linkedlist l1, linkedlist l2

java linkedlist merge(linkedlist l1, linkedlist l2)

Problem Discription

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.

Java Programming
  1. /*
  2. * Merge two sorted linked lists
  3. * and return it as a new list.
  4. * The new list should be made
  5. * by splicing together the nodes of the first two lists.
  6. *
  7. * */
  8. class ListNode
  9. {
  10. int val;
  11. ListNode next;
  12. ListNode(int x)
  13. {
  14. val = x;
  15. }
  16. }
  17. public class Ans21_Merge_Two_Sorted_Lists
  18. {
  19. public ListNode mergeTwoLists(ListNode l1, ListNode l2)
  20. {
  21. if (l1 == null && l2 == null)
  22. {
  23. return null;
  24. }
  25. ListNode lm = new ListNode(0);
  26. ListNode head = lm;
  27. while (l1 != null && l2 != null)
  28. {
  29. if (l1.val <= l2.val)
  30. {
  31. lm.next = l1;
  32. l1 = l1.next;
  33. }
  34. else
  35. {
  36. lm.next = l2;
  37. l2 = l2.next;
  38. }
  39. lm = lm.next;
  40. }
  41. if (l1 == null)
  42. {
  43. lm.next = l2;
  44. }
  45. else if (l2 == null)
  46. {
  47. lm.next = l1;
  48. }
  49. return head.next;
  50. }
  51. }


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

闽ICP备14008679号