fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. class ListNode {
  8. public int val;
  9. public ListNode next;
  10.  
  11. public ListNode(int x) {
  12. val = x;
  13. }
  14. }
  15.  
  16. /* Name of the class has to be "Main" only if the class is public. */
  17. class Ideone
  18. {
  19. public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
  20.  
  21. // Create a sentinal/dummy node to start
  22. ListNode returnNode = new ListNode(Integer.MIN_VALUE);
  23.  
  24. // Create a copy of this node to iterate while solving the problem
  25. ListNode headNode = returnNode;
  26.  
  27. // Traverse till one of the list reaches the end
  28. while (l1 != null && l2 != null) {
  29.  
  30. // Compare the 2 values of lists
  31. if (l1.val <= l2.val) {
  32. returnNode.next = l1;
  33. l1 = l1.next;
  34. } else {
  35. returnNode.next = l2;
  36. l2 = l2.next;
  37. }
  38. returnNode = returnNode.next;
  39. }
  40.  
  41. // Append the remaining list
  42. if (l1 == null) {
  43. returnNode.next = l2;
  44. } else if (l2 == null) {
  45. returnNode.next = l1;
  46. }
  47.  
  48. // return the next node to sentinal node
  49. return headNode.next;
  50. }
  51.  
  52. public static void main (String[] args) throws java.lang.Exception
  53. {
  54. // your code goes here
  55. Ideone x = new Ideone();
  56. ListNode l1 = new ListNode(1);
  57. l1.next = new ListNode(2);
  58. l1.next.next = new ListNode(4);
  59.  
  60. ListNode l2 = new ListNode(1);
  61. l2.next = new ListNode(3);
  62. l2.next.next = new ListNode(4);
  63.  
  64. ListNode listNode = x.mergeTwoLists(l1, l2);
  65.  
  66. while(listNode != null) {
  67. System.out.print(listNode.val + " -> ");
  68. listNode = listNode.next;
  69. }
  70. }
  71. }
Success #stdin #stdout 0.08s 33968KB
stdin
Standard input is empty
stdout
1 -> 1 -> 2 -> 3 -> 4 -> 4 ->