Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- import java.lang.*;
- import java.io.*;
- //Node static head;
- class Node{
- int data;
- Node next;
- Node(int val){
- data=val;
- }
- }
- class Linkedlist{
- Node head;
- void Insert(int data){
- Node newnode=new Node(data);
- if(head==null){
- head=newnode;
- return;
- }
- Node temp=head;
- while(temp.next!=null){
- temp=temp.next;
- }
- temp.next=newnode;
- }
- Node merge(Node head1,Node head2){
- Node list=new Node(-1);
- Node ans=list;
- Node temp1=head1;
- Node temp2=head2;
- while(temp1!=null && temp2!=null){
- if(temp1.data<temp2.data){
- list.next=new Node(temp1.data);
- temp1=temp1.next;
- }
- else{
- list.next=new Node(temp2.data);
- temp2=temp2.next;
- }
- list=list.next;
- }
- //list=list.next;
- if(temp1!=null) list.next=temp1;
- if(temp2!=null) list.next=temp2;
- return ans.next;
- }
- void print(){
- //head=list;
- Node temp=head;
- while(temp!=null){
- System.out.print(temp.data+" ");
- temp=temp.next;
- }
- System.out.println();
- }
- }
- public class Main
- {
- public static void main (String[] args) throws java.lang.Exception
- {
- //your code here
- Scanner sc=new Scanner(System.in);
- Linkedlist l=new Linkedlist();
- Linkedlist l1=new Linkedlist();
- Linkedlist l2=new Linkedlist();
- int list_size1=sc.nextInt();
- for(int i=0; i<list_size1; i++){
- l1.Insert(sc.nextInt());
- }
- int list_size2=sc.nextInt();
- for(int i=0; i<list_size2; i++){
- l2.Insert(sc.nextInt());
- }
- Node head1=l1.head;
- Node head2=l2.head;
- Node ans=l1.merge(head1,head2);
- while(ans!=null) {
- System.out.print(ans.data+" ");
- ans=ans.next;
- }
- // Node dummy=new Nodehead1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement