Advertisement
Khadija_Assem

Untitled

Jan 16th, 2020
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  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. class Solution {
  10. public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  11. ListNode n = null;
  12. ListNode N = null;
  13. if (l1 == null){
  14. return l2;
  15. }
  16. else if (l2 == null){
  17. return l1;
  18. }
  19. if (l1 != null && l2 != null){
  20. if (l1.val < l2.val){
  21. n = l1;
  22. l1 = l1.next;
  23. N = n;
  24. }
  25. else if (l1.val > l2.val){
  26. n = l2;
  27. l2 = l2.next;
  28. N = n;
  29. }
  30. else if (l1.val == l2.val){
  31. n = l1;
  32. l1 = l1.next;
  33. N = n;
  34. N.next = l2;
  35. N = l2;
  36. l2 = l2.next;
  37. }
  38. }
  39. while (l1 != null && l2 != null){
  40. if (l1.val < l2.val){
  41. N.next = l1;
  42. N = l1;
  43. l1 = l1.next;
  44. }
  45. else if (l1.val > l2.val){
  46. N.next = l2;
  47. N = l2;
  48. l2 = l2.next;
  49. }
  50. else if (l1.val == l2.val){
  51. N.next = l1;
  52. N = l1;
  53. l1 = l1.next;
  54. N.next = l2;
  55. N = l2;
  56. l2 = l2.next;
  57. }
  58. }
  59. while (l1 != null){
  60. N.next = l1;
  61. N = l1;
  62. l1 = l1.next;
  63. }
  64. while (l2 != null){
  65. N.next = l2;
  66. N = l2;
  67. l2 = l2.next;
  68. }
  69. return n;
  70. }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement