Write a Java program to clone an linked list to another linked list


The Java code provided demonstrates how to clone a linked list using the clone method.

  • The code defines a class named Clone_LinkedList with a main method, which serves as the entry point for the Java program.
  • Inside the main method, a LinkedList object named b_list is created with a type parameter of String, indicating that it will store strings as its elements.
  • Strings such as "Java", "C", "Cpp", "Python", and "Php" are added to b_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 initial contents of b_list before cloning.
  • A new LinkedList object named new_list is created with a type parameter of String, which will store the cloned elements.
  • The b_list.clone() method is called to create a shallow copy of b_list using the clone method. The clone method creates a new linked list object that contains the same elements as the original linked list, but the objects themselves are not deep copied, meaning they still refer to the same objects in memory as the original list.
  • The new_list object is then assigned the cloned linked list object using the assignment operator (=).
  • The System.out.println statement is used to print the contents of the cloned linked list new_list.v
  • The output of the program will be the initial contents of b_list printed on the first line, followed by the message "Cloned linked list : " printed on the second line with the contents of the cloned linked list new_list.

Source Code

import java.util.*;
public class Clone_LinkedList
{
	public static void main(String[] args) 
	{
		LinkedList <String> b_list = new LinkedList <String> ();
		b_list.add("Java");
		b_list.add("C");
		b_list.add("Cpp");
		b_list.add("Python");
		b_list.add("Php");
		System.out.println("Given linked  list : " + b_list);
		LinkedList <String> new_list = new LinkedList <String> ();
		new_list = (LinkedList)b_list.clone();
		System.out.println("Cloned linked list : " + new_list);       
	}
}

Output

Given linked  list : [Java, C, Cpp, Python, Php]
Cloned linked list : [Java, C, Cpp, Python, Php]

Example Programs