Write a Java program to join two linked lists


The Java code provided demonstrates how to join two linked lists using the addAll method.

  • The code defines a class named JoinTwo_LinkedList with a main method, which serves as the entry point for the Java program.
  • Inside the main method, two LinkedList objects named b1_list and b2_list are created with a type parameter of String, indicating that they will store strings as their elements.
  • Strings such as "Java", "Cpp", "Python", and "Php" are added to b1_list using the add method, which appends the elements to the end of the list.
  • The System.out.println statement is used to print the contents of b1_list before joining.
  • Strings such as "C", "Html", "MySql", and "Php" are added to b2_list using the add method, which appends the elements to the end of the list.
  • The System.out.println statement is used to print the contents of b2_list before joining.
  • A new LinkedList object named a is created with a type parameter of String, which will store the combined elements of b1_list and b2_list.
  • The a.addAll(b1_list) method is called to add all the elements of b1_list to the end of a using the addAll method. This effectively joins b1_list and b2_list together.
  • The a.addAll(b2_list) method is then called to add all the elements of b2_list to the end of a using the addAll method.
  • The System.out.println statement is used to print the contents of the combined linked list a.
  • The output of the program will be the contents of b1_list printed on the first line, followed by the contents of b2_list printed on the second line, and finally the message "New linked list: " printed on the third line with the contents of the combined linked list a.

Source Code

import java.util.*;
public class JoinTwo_LinkedList
{
	public static void main(String[] args)
	{
		LinkedList <String> b1_list = new LinkedList <String> ();
		b1_list.add("Java");
		b1_list.add("Cpp");
		b1_list.add("Python");
		b1_list.add("Php");
		System.out.println("List of first linked list: " + b1_list);
		LinkedList <String> b2_list = new LinkedList <String> ();
		b2_list.add("C");
		b2_list.add("Html");
		b2_list.add("MySql");
		b2_list.add("Php");
		System.out.println("List of second linked list: " + b2_list);
		LinkedList <String> a = new LinkedList <String> ();
		a.addAll(b1_list);
		a.addAll(b2_list);
		System.out.println("New linked list: " + a);
	}
}

Output

List of first linked list: [Java, Cpp, Python, Php]
List of second linked list: [C, Html, MySql, Php]
New linked list: [Java, Cpp, Python, Php, C, Html, MySql, Php]

Example Programs