w3resource

Java Exercises: Merge two sorted (ascending) linked lists in ascending order

Java Basic: Exercise-207 with Solution

Write a Java program to merge two sorted (ascending) linked lists in ascending order.

Sample Solution:

Java Code:

import java.util.*;
class Main
{
    public static void main(String[] args)  
    {
      //Create the 1st linked list and take input as per user's choice
        LinkedList  list1 = new LinkedList();
        Scanner input = new Scanner(System.in);
        System.out.print("How many elements do you want to add in 1st linked list?: ");
        int num = input.nextInt();
        System.out.print("Input numbers of 1st linked list in ascending order: ");
        for(int i=0;i<num;i++)
        {
         int element = input.nextInt();
         list1.add(element);
        }
        System.out.println();
       //System.out.println("Elements of 1st linked list are: ");
       //for(int i=0;i<list.size();i++){
       //System.out.println(list.get(i));}       
       //Convert the 1st linked list to arraylist
       List<Integer> list1_1 = new ArrayList<Integer>(list1);
       //Convert the arraylist to array using toArray method
        Object[] list1_1_1 = list1_1.toArray();
       //Copy elements from object array to integer array
        int[] list1_1_1_1 = new int[list1_1_1.length];
       	for (int i = 0; i < list1_1_1.length; i++)
		   	list1_1_1_1[i] = (int)list1_1_1[i];	   	
//Create the 2nd linked list and take input as per user's choice
        LinkedList list2 = new LinkedList();
        System.out.print("How many elements do you want to add in 2nd linked list?: ");
        int num1 = input.nextInt();
        System.out.print("Input numbers of 2nd linked list in ascending order: ");
        for(int i=0;i<num1;i++)
        {
         int element = input.nextInt();
         list2.add(element);
        }
        System.out.println();
       //System.out.println("Elements of 2nd linked list are: ");
       //for(int i=0;i<list1.size();i++){
       //System.out.println(list1.get(i));}       
       //Convert the 2nd linked list to arraylist
       List<Integer> list2_2 = new ArrayList<Integer>(list2);
       //Convert the arraylist to array using toArray method
        Object[] list2_2_2 = list2_2.toArray();
    	 //Copy elements from object array to integer array
	      int[] list2_2_2_2 = new int[list2_2_2.length];
        for (int i=0; i<list2_2_2.length; i++)
			       list2_2_2_2[i] = (int)list2_2_2[i];      
       int[] mergedArray = merge(list1_1_1_1, list2_2_2_2);
      System.out.print("Merged list: ");
      for (int i=0; i<mergedArray.length; i++)
      {
        System.out.print(mergedArray[i] + " ");
      }    
    }
//Create java method to merge the elements of 2 linked lists
public static int[] merge(int[] list1_1_1_1, int[] list2_2_2_2) 
    {
//Create an array listmerged of length list1_1_1_1.length+list2_2_2_2.length and arrange the eliments in ascending order
      int[] listmerged = new int[list1_1_1_1.length + list2_2_2_2.length];
      int i = 0, j = 0, k = 0;
      while (i < list1_1_1_1.length && j < list2_2_2_2.length)
      {
          if (list1_1_1_1[i] < list2_2_2_2[j])
          {
              listmerged[k] = list1_1_1_1[i];
              i++;
          }
          else
          {
              listmerged[k] = list2_2_2_2[j];
              j++;
          }
          k++;
      }
      while (i < list1_1_1_1.length)
      {
          listmerged[k] = list1_1_1_1[i];
          i++;
          k++;
      }
      while (j < list2_2_2_2.length)
      {
          listmerged[k] = list2_2_2_2[j];
          j++;
          k++;
      }
      return listmerged;
    }
}

Output:

How many elements do you want to add in 1st linked list?:  3
Input numbers of 1st linked list in ascending order:  1 2 3

How many elements do you want to add in 2nd linked list?:  3
Input numbers of 2nd linked list in ascending order:  3 4 5

Merged list: 1 2 3 3 4 5 

Flowchart:

Flowchart: Java exercises: Write a Java program to merge two sorted (ascending) linked lists in ascending order.
Flowchart: Java exercises: Write a Java program to merge two sorted (ascending) linked lists in ascending order.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to find all unique combinations from a collection of candidate numbers. The sum of the numbers will be equal to a given target number.
Next: Write a Java program to create a basic string compression method using the counts of repeated characters.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

Java: Tips of the Day

Java: Anagrams

Generates all anagrams of a string.

public static List<String> anagrams(String input) {
    if (input.length() <= 2) {
        return input.length() == 2
                ? Arrays.asList(input, input.substring(1) + input.substring(0, 1))
                : Collections.singletonList(input);
    }
    return IntStream.range(0, input.length())
            .mapToObj(i -> new SimpleEntry<>(i, input.substring(i, i + 1)))
            .flatMap(entry ->
                    anagrams(input.substring(0, entry.getKey()) + input.substring(entry.getKey() + 1))
                            .stream()
                            .map(s -> entry.getValue() + s))
            .collect(Collectors.toList());
}

Ref: https://bit.ly/3rvAdAK