Advertisement
unknown_0711

Untitled

Jul 20th, 2022
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4. //Node static head;
  5. class Node{
  6. int data;
  7. Node next;
  8. Node(int val){
  9. data=val;
  10. }
  11. }
  12. class Linkedlist{
  13. Node head;
  14. void Insert(int data){
  15. Node newnode=new Node(data);
  16. if(head==null){
  17. head=newnode;
  18. return;
  19. }
  20. Node temp=head;
  21. while(temp.next!=null){
  22. temp=temp.next;
  23. }
  24. temp.next=newnode;
  25. }
  26. Node merge(Node head1,Node head2){
  27. Node list=new Node(-1);
  28. Node ans=list;
  29. Node temp1=head1;
  30. Node temp2=head2;
  31. while(temp1!=null && temp2!=null){
  32. if(temp1.data<temp2.data){
  33. list.next=new Node(temp1.data);
  34. temp1=temp1.next;
  35. }
  36. else{
  37. list.next=new Node(temp2.data);
  38. temp2=temp2.next;
  39. }
  40. list=list.next;
  41. }
  42. //list=list.next;
  43. if(temp1!=null) list.next=temp1;
  44. if(temp2!=null) list.next=temp2;
  45.  
  46. return ans.next;
  47. }
  48. void print(){
  49. //head=list;
  50. Node temp=head;
  51. while(temp!=null){
  52. System.out.print(temp.data+" ");
  53. temp=temp.next;
  54. }
  55. System.out.println();
  56. }
  57. }
  58. public class Main
  59. {
  60. public static void main (String[] args) throws java.lang.Exception
  61. {
  62. //your code here
  63. Scanner sc=new Scanner(System.in);
  64.  
  65. Linkedlist l=new Linkedlist();
  66. Linkedlist l1=new Linkedlist();
  67. Linkedlist l2=new Linkedlist();
  68.  
  69. int list_size1=sc.nextInt();
  70. for(int i=0; i<list_size1; i++){
  71. l1.Insert(sc.nextInt());
  72. }
  73.  
  74. int list_size2=sc.nextInt();
  75. for(int i=0; i<list_size2; i++){
  76. l2.Insert(sc.nextInt());
  77. }
  78.  
  79. Node head1=l1.head;
  80. Node head2=l2.head;
  81. Node ans=l1.merge(head1,head2);
  82. while(ans!=null) {
  83. System.out.print(ans.data+" ");
  84. ans=ans.next;
  85. }
  86. // Node dummy=new Nodehead1;
  87.  
  88.  
  89. }
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement