fork(2) download
  1. class Node {
  2.  
  3. Node next;
  4. int value;
  5.  
  6. Node(int val) {
  7. this.value = val;
  8. this.next = null;
  9. }
  10.  
  11. @Override
  12. public String toString() {
  13. Node cur = this;
  14. String str = "";
  15.  
  16. while(cur != null) {
  17. str += cur.value+"->";
  18. cur = cur.next;
  19. }
  20.  
  21. return str;
  22. }
  23. }
  24.  
  25. class MergeLL {
  26.  
  27. public static Node merge(Node n1, Node n2) {
  28.  
  29. Node result = null;
  30.  
  31. if(n1 != null && n2 != null) {
  32. if(n1.value < n2.value) {
  33. result = n1;
  34. result.next = merge(n1.next, n2);
  35. } else {
  36. result = n2;
  37. result.next = merge(n1, n2.next);
  38. }
  39. } else if(n1!=null ){
  40. result=n1;
  41. } else if(n2!=null){
  42. result=n2;
  43. }
  44. return result;
  45. }
  46.  
  47. public static void main(String[] args) {
  48. Node n1 = new Node(1);
  49. Node n3 = new Node(3);
  50. Node n5 = new Node(5);
  51. Node n7 = new Node(7);
  52. Node n9 = new Node(9);
  53.  
  54. n1.next = n3;
  55. n3.next = n5;
  56. n5.next = n7;
  57. n7.next = n9;
  58. n9.next = null;
  59.  
  60. Node n2 = new Node(2);
  61. Node n4 = new Node(4);
  62. Node n6 = new Node(6);
  63. Node n8 = new Node(8);
  64. Node n10 = new Node(10);
  65.  
  66. n2.next = n4;
  67. n4.next = n6;
  68. n6.next = n8;
  69. n8.next = n10;
  70. n10.next = null;
  71.  
  72. System.out.println("Merge : " + merge(n1, n2));
  73. }
  74. }
  75.  
Success #stdin #stdout 0.07s 380160KB
stdin
Standard input is empty
stdout
Merge : 1->2->3->4->5->6->7->8->9->10->